Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - How to apply different class in <tr> conditionally to repeat directive

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?

like image 762
Aitiow Avatar asked Sep 16 '12 13:09

Aitiow


2 Answers

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

like image 196
pkozlowski.opensource Avatar answered Oct 13 '22 01:10

pkozlowski.opensource


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

like image 39
The Who Avatar answered Oct 13 '22 02:10

The Who