Introduction
The ng-repeat directive is most used and very useful AngularJS Directive. It iterates over a collection of items and creates DOM elements. It constantly monitors the source of data to re-render a template in response to change.
Syntax of ng-repeat:
- <table class="table table-bordered">
- <tr ng-repeat="empin empDetails">
- <td>{{emp.name}}</td>
- <td>{{emp.salary}}</td>
- </tr>
- </table>
Here, ng-repeat directive iterates over the empDetails collection and creates a <tr> DOM element for each entry in the collection.
The ng-repeat directive creates a new scope for each element of a collection.
Variables create by ng-repeat
AngularJS ng-repeat directive creates so many special variables in a scope created for each and every individual entry. These variables are very important to find the position of an element within a collection.
Below are the some important variables created by ng-repeat:
- $index
- $first
- $middle
- $last
$index
$index sets index from 0. It indicates the indexes of an element created by ng-repeat. So, it is used to get a numerical position of a given property in a sorted list of all properties.
Example:
- <li ng-repeat="emp in employeeDetails">
- Index: {{$index}}
- </li>
Output:
Suppose that collection "employeeDetails" has five items then it will show like below:
$first, $middle, $last
These variables gives output as a Boolean value according to element position.
Example:
- <li ng-repeat="emp in employeeDetails"> <span class="divider">/</span>
- <ng-switch on="$last"> <span ng-switch-when="true">{{emp.name}}</span> <span ng-switch-default>
- <a href="{{emp.path}}">{{emp.name}}</a>
- </span> </ng-switch>
- </li>
- var app = angular.module('plunker', []);
-
- app.controller('MainCtrl', function($scope) {
- $scope.employeeDetails = [
- {name:"label", path: "label"},
- {name:"notes", path: "notes"}
- ]
- });
Plunker Link.
Apply Dynamic CSS
We can apply dynamic CSS conditionally in ng-repeat.
Example:
- <tr ng-repeat="emp in employeeDetails"
- ng-class-even="'light-gray'" ng-class-odd="'dark-gray'">
- . . .
- </tr>
- <tr ng-repeat="emp in myEmployee"
- ng-class="{'dark-gray' : !$index%2, 'light-gray' : $index%2}">
Conclusion
So, ng-repeat is a powerful directive to iterate collection item over DOM. It creates DOM by iterating.