Saqib Ali
Saqib Ali

Reputation: 12635

Angular: How to alternate CSS classes for a list, with more than 2 classes?

I have the following Angular template. This nicely alternates the style class of each row such that even-numbered rows have one class and odd-numbered rows have a different class:

<tbody>
  <tr ng-repeat="currElement in myCtrl.elementList track by $index" >
    <td ng-class-odd="'element-tilt-left'" ng-class-even="'element-tilt-right'">
      <a ui-sref="myState({elementId: currElement.elementId)" ng-bind="currElement.name">
      </a>
    </td>
  </tr>
</tbody>

But now I want to cycle among 4 different style classes instead of just two. How can I do it?

Upvotes: 2

Views: 416

Answers (4)

Samuel
Samuel

Reputation: 1426

Hope this would be helpful.

.row:nth-child(4n+1){
  color: red;
}

.row:nth-child(4n+2){
  color: green;
}

.row:nth-child(4n+3){
  color: grey;
}

.row:nth-child(4n+4){
  color: blue;
}

This would save the angular digest cycle

Upvotes: 0

Phil
Phil

Reputation: 165059

You should be able to use CSS only with the nth-child selector...

angular.module('so', []).run(function($rootScope) {
  $rootScope.elementList = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(i) {
    return { name: 'Item ' + i };
  });
});
tr:nth-child(4n-3) td {
  background-color: red;    /* Style #1 */
}
tr:nth-child(4n-2) td {
  background-color: green;  /* Style #2 */
}
tr:nth-child(4n-1) td {
  background-color: blue;   /* Style #3 */
  color: white;
}
tr:nth-child(4n) td {
  background-color: black;  /* Style #4 */
  color: white;
}
<table ng-app="so">
  <tbody>
    <tr ng-repeat="currElement in elementList track by $index">
      <td>
        <a ng-bind="currElement.name"></a>
      </td>
    </tr>
  </tbody>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

Upvotes: 4

grayimp
grayimp

Reputation: 368

I like Divyanshu's answer, but instead of listing all the classes would suggest just computing the class name inline like:

ng-class="'class' + $index%4"

Here is an update to his fiddle: http://jsfiddle.net/uL5zd8sy/1/

Upvotes: 5

Divyanshu Maithani
Divyanshu Maithani

Reputation: 15036

You could try something like:

ng-class="{class1 : $index%4 == 0, class2 : $index%4 == 1, class3 : $index%4 == 2, class4 : $index%4 == 3}"

Check out this fiddle.

Upvotes: 2

Related Questions