Posted by Arjun on Thursday 18th December 2014

How to assign alternate class to rows in Angular JS?

Intermediate Angular Js Anguarl Js Filter

In this post i would like to write about Angular JS ngClassOdd,ngClassEven directives , by using this directories we can take effect only on odd rows or on even rows.

This directives work exactly as ngClass and this directives only work when they are in scope of an ngRepeat.

For example by using ngClassOdd,ngClassEven directives we gonna add alternate row colors in table.

First create css, for applying different color to each type, blow is the css.

.even {
 background-color: #ccc;
}
.odd {
 background-color: #333;
}

Angular Table :

<table ng-app  ng-init="countries = ['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba','Australia','Austria','Azerbaijan']" >
                <tr ng-repeat="country in countries" ng-class-odd="'odd'" ng-class-even="'even'">
                    <td>{{country}}</td>
                </tr>
 </table>

In the above script :
The ng-app directive initializes an AngularJS application.
The ng-init directive initialize application data.
The ng-repeat directive clones HTML elements once for each item in an array or in an object.
The ng-class-odd directive effect only the odd rows in the ng-repeat clone.
The ng-class-even directive effect only the even rows in the ng-repeat clone.

Complete Example

<!doctype html>
<html>
<head>
<title>Angularjs Alternate Rows of Table - arjunphp.com</title>
	<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
    <style>
    .odd {
        background-color: #afb5ff;
    }
    .even {
        background-color: #ccc;
    }
    </style>
</head>
<body>
<table ng-app  ng-init="countries = ['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba','Australia','Austria','Azerbaijan']" >
  <tr ng-repeat="country in countries" ng-class-odd="'odd'" ng-class-even="'even'">
    <td>{{country}}</td>
  </tr>
</table>
<a href="https://arjunphp.com/" target="_blank">arjunphp.com</a>
</body>
</html>

That's it , to see the demo click on below demo link.