10

I need to apply a different class to a <tr> according to the $index of the repeat directive. For example

<table>
   <tr ng-repeat="model in list" class="xxx">
       <td>...</td>
   <tr>
</table>

I need to apply a different style to <tr> depending on whether the index is even and odd.

How could I solve this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Aitiow
  • 882
  • 2
  • 9
  • 18

2 Answers2

22

Normally you would use ngClassOdd (http://docs.angularjs.org/api/ng.directive:ngClassOdd) and ngClassEven (http://docs.angularjs.org/api/ng.directive:ngClassEven) directives like this:

<tr ng-repeat="item in items" ng-class-odd="'class1'" ng-class-even="'class2'">

Here is the jsFiddle: http://jsfiddle.net/pkozlowski_opensource/hNHJ4/1/

Unfortunately there is an issue where the mentioned directives are not working correctly when rows are removed: https://github.com/angular/angular.js/issues/1076

As a work around you can use the ngClass directive (http://docs.angularjs.org/api/ng.directive:ngClass) with the $index variable exposed by a repeater:

<tr ng-repeat="item in items" ng-class="{class1 : $index%2==0, class2 : !($index%2==0)}">

Here is the jsFiddle: http://jsfiddle.net/pkozlowski_opensource/am7xs/

It is not super-clean, but could be improved (for example, by exposing a function in a root scope, something like:

ng-class="getClass($index,'class1','class2')"

till the mentioned bug is fixed

pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
  • I wonder if its possible to append a TR that goes outside the grain of the other TR's.. preferably one with a title header. Like every row is a week, and then a TR is a header for that month or that year but doesn't contain 7 TD's.. I'm getting that this is impossible to do with Angular.. – Trip Jan 21 '13 at 21:26
  • I would put the "bug is fixed" line before explaining how to work around, emphasized. – Oded Niv Jul 14 '15 at 10:31
5

If this is just for styling you can just use CSS

tr:nth-child(odd) { ... }
tr:nth-child(even) {...}

see http://jsfiddle.net/5MSDC/ for an example

The Who
  • 6,552
  • 5
  • 36
  • 33
  • Actually this is the correct way of doing it. Since it's a CSS class thing, CSS is the best way to do it. – Idrees Apr 07 '15 at 15:35
  • 1
    The Who, you've got a typo: tr:nth-child(event) {...} .. it should be even not event. – Idrees Apr 07 '15 at 15:37