How to combine these 2 ng-class statements?

380 views Asked by At
<ul>
    <li ng-repeat="(k, v) in chartTags track by k" class="blue-tag">
        <div class="tag"
             ng-class="{blue1: k == 0 , blue2: k == 1 , blue3: k == 2 }"
             ng-class="{'positive': v.direction == 'positive',
                        'negative': v.direction == 'negative',
                        ''        : v.direction == 'stagnant'}">{{v.term}}</div>
    </li>
</ul>

Currently the first ng-class overrides the 2nd ng-class I have. How would you combine both of these, so that I get a blue class of some sort, as well as a direction type?

2

There are 2 answers

0
area28 On BEST ANSWER

Chain them together as you did with the first one.

<div class="tag" ng-class="{blue1: k == 0 , blue2: k == 1 , blue3: k == 2, 'positive': v.direction == 'positive',
                    'negative': v.direction == 'negative',
                    '' : v.direction == 'stagnant'}">
</div>

It won't stop evaluating so you can have multiple classes.

Here is another SO post about adding multiple classes with ng-class.

0
PSL On

You could use an array and make the expression much concise and readable:

      <div class="tag"
         ng-class="[{0:'blue1', 1:'blue2', 2:'blue3'}[k], v.direction]">{{v.term}}</div>

You just have to take care of "stagnant" class being set via css (or do [{0:'blue1', 1:'blue2', 2:'blue3'}[k], v.direction === 'stagnant' ? '' : v.direction]). ng-class is flexible that you can use an array of expression or string as well. In this case first value in the array is an object literal {0:'blue1', 1:'blue2', 2:'blue3'}[k] with a bracket notation to evaluate the value out of the array based on the key passed in by k and second value of array is the v.direction itself.

Demo

.blue1 {
  color: blue;
}
.blue2 {
  color: green;
}
.blue1 {
  color: red;
}
.negative {
  background-color: #ccc;
}
.positive {
  background-color: #123;
}
.stagnant {
  background-color: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app ng-init="k=1;v.direction='positive'">
  <div class="tag" ng-class="[{0:'blue1', 1:'blue2', 2:'blue3'}[k], v.direction]">Term</div>

</div>

Sometimes a general thumb rule is that when you have a longer expression it should not be in the view, instead should be in the controller. So you could as well create a controller function and return the expected classes as an object literal and bind the function to ng-class.