In Focus

AngularJS ngRepeat Directive

This blog is intended to explain the concept of AngularJS ng-repeat Directive.

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:

  1. <table class="table table-bordered">  
  2.     <tr ng-repeat="empin empDetails">  
  3.         <td>{{emp.name}}</td>  
  4.         <td>{{emp.salary}}</td>  
  5.     </tr>  
  6. </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:

 

  1. $index
  2. $first
  3. $middle
  4. $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:

  1. <li ng-repeat="emp in employeeDetails">    
  2.   Index: {{$index}}     
  3. </li>   
Output:

Suppose that collection "employeeDetails" has five items then it will show like below:

 

    Index: 0
    Index: 1
    Index: 2
    Index: 3
    Index: 4

$first, $middle, $last

These variables gives output as a Boolean value according to element position.

Example:

  1. <li ng-repeat="emp in employeeDetails"> <span class="divider">/</span>  
  2.     <ng-switch on="$last"> <span ng-switch-when="true">{{emp.name}}</span> <span ng-switch-default>    
  3.      <a href="{{emp.path}}">{{emp.name}}</a>    
  4.    </span> </ng-switch>  
  5. </li>  
  1. var app = angular.module('plunker', []);    
  2.     
  3. app.controller('MainCtrl', function($scope) {    
  4.   $scope.employeeDetails = [    
  5.     {name:"label", path: "label"},    
  6.     {name:"notes", path: "notes"}    
  7. ]    
  8. });    
Plunker Link.

Apply Dynamic CSS

We can apply dynamic CSS conditionally in ng-repeat.

Example:
  1. <tr ng-repeat="emp in employeeDetails"    
  2. ng-class-even="'light-gray'" ng-class-odd="'dark-gray'">    
  3. . . .    
  4. </tr>    
  5. <tr ng-repeat="emp in myEmployee"    
  6. 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.