3

I have a list which is limited to 3 items, the first item needs class blue1, 2nd needs blue2, 3rd 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 }"

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

3 Answers3

4

I think you could solve this by no need to use track by $index as such 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>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Thanks, that does work too :) I had to make the first `k == 0` I like that index syntax, is there a name for it? `(k, v) in chartTags` very clean. – Leon Gaban Apr 23 '15 at 15:30
  • 1
    `(k, v)` are like key value pair of array if its json like `{"a":"1"}` then `a` would be `k` & `v` would be `1` & in array `["1","2","3"]` object `k` would be `0` & `v` would be `1` same for other element – Pankaj Parkar Apr 23 '15 at 15:35
  • this will not work in the case of duplication.if you have same(duplicate) item in an array like [1,1,2,3]. in that case it will throw error. – Mukund Kumar Apr 23 '15 at 15:47
1

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

Mukund Kumar
  • 21,413
  • 18
  • 59
  • 79
  • Hmm just tried that, but got a parse error `Syntax Error: Token '' {1} at column {2} of the expression [{3}] starting at [{4}].` – Leon Gaban Apr 23 '15 at 15:05
  • i have created plunker for you.here it is working: http://plnkr.co/edit/ffPuIyORFIIHMAYCpPyE – Mukund Kumar Apr 23 '15 at 15:15
  • 1
    Thanks! Your original code would have worked with just this: `
    {{tag.term}}
    ` needed the first item to be `0` and also `,` not `||`
    – Leon Gaban Apr 23 '15 at 15:18
1

first you have to track index using track by and use , to seperate class conditions and 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>
Yogesh Khatri
  • 1,180
  • 8
  • 11