To simplify and enhance readability, consider utilizing an array for the expression:
<div class="tag"
ng-class="[{0:'blue1', 1:'blue2', 2:'blue3'}[k], v.direction]">{{v.term}}</div>
Make sure to account for the "stagnant" class being applied through CSS (or use
[{0:'blue1', 1:'blue2', 2:'blue3'}[k], v.direction === 'stagnant' ? '' : v.direction]
). With
ng-class
, you have the flexibility to utilize either an array of expressions or strings. In this scenario, the first value in the array is an object literal
{0:'blue1', 1:'blue2', 2:'blue3'}[k]
, which retrieves the corresponding value based on the key provided by
k
. The second value in the array is simply
v.direction
.
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>
In situations where you have lengthy expressions, it is often recommended to keep them out of the view and instead handle them within the controller. You can create a controller function that returns the desired classes as an object literal, then bind the function to ng-class
.