How to use $ index to change class in ng-repeat?
I have a list that is limited to three elements, the first element needs a class blue1
, the second one blue2
, the third one blue3
.
<ul>
<li ng-repeat="tag in chartTags" class="blue-tag">
<div class="tag blue1" ng-class="{blue1: tag == 1 }">{{tag.term}}</div>
</li>
<!-- <li><div class="tag blue1">item1</div></li>
<li><div class="tag blue2">item2</div></li>
<li><div class="tag blue3">item3</div></li> -->
</ul>
Is there a way to write a check like ng-class="{blue1: tag == 1 || blue2: tag == 2 || blue3: tag == 3 }"
I think you could solve this problem without having to use a track $index
since you don't have duplicates.
Markup
<li ng-repeat="(k, v) in chartTags" class="blue-tag">
<div ng-class="{blue1: k == 1 , blue2: k == 2 , blue3: k == 3 }">{{v.term}}</div>
</li>
use $index
.
<ul>
<li ng-repeat="tag in chartTags track by $index" class="blue-tag">
<div class="tag " ng-class="{blue1: $index== 0 ,blue2: $index== 1 ,blue3: $index== 2 }">{{tag.term}}</div>
</li>
</ul>
See plunker
first you need to track the index with track by
and use ,
to separate class conditions, not||
like this
<li ng-repeat="tag in chartTags track by $index" class="blue-tag">
<div class="tag" ng-class="{blue1: $index == 0, blue2: $index == 1, blue3: $index == 2 }">{{tag}}</div>
</li>