RudziankoŇ≠ RudziankoŇ≠ - 3 months ago 14
AngularJS Question

AngularJS: Conditional ng-class with several matches for one option.

I have following snippet:

<span class="label"
ng-class="{
'label-success': resp.level == 'A1',
'label-success': resp.level == 'A2',
'label-warning': resp.level == 'B1',
'label-warning': resp.level == 'B2',
'label-danger': resp.level == 'C1',
'label-danger': resp.level == 'C2',
'label-default': resp.level == 'This word was not found',
'label-default': resp.level == 'The word level is not known'}">{[{resp.level}]}</span>


It doesn't work, seems because of several matches for the same option.
This is work fine:

<span class="label"
ng-class="{
'label-success': resp.level == 'A1',
'label-warning': resp.level == 'B1',
'label-danger': resp.level == 'C1',
'label-default': resp.level == 'The word level is not known'}">{[{resp.level}]}</span>


Questions:


  • What is the reason?

  • How to fix this?


Answer

First one is not working because we are making object having duplicate key which is not allowed use

<span class="label"
          ng-class="{
          'label-success': (resp.level == 'A1' ||resp.level == 'A2'),

          'label-warning': (resp.level == 'B1' ||resp.level == 'B2'),

          'label-danger': (resp.level == 'C1' ||resp.level == 'c2'),

          'label-default': (resp.level == 'This word was not found' ||resp.level == 'The word level is not known')
          }">{[{resp.level}]}</span>