ng-repeat Directive In Angularjs

AngularJS provides the concepts of Directives, which are basically nothing but extending the html attributes. Some of these directives include ng-init, ng-app and ng-repeat. We will discuss the concept of ng-repeat in this article.
 
ng-repeat article is basically used to bind list/array of data to html controls. For ex. we have a list of Employees which we want to bind in html table or div. Then we can use the ng-repeat directive to do this. So let's start by creating an angular controller and add some data in list of Employees. So our controller will look like the following: 
  1. var app = angular.module("mainApp", []);  
  2.         app.controller('ngRepeatController'function ($scope, $http) {  
  3.   
  4.             $scope.EmpList = [];  
  5.   
  6.             $scope.EmpList.push({ Id: 1, Name: 'User A' });  
  7.             $scope.EmpList.push({ Id: 2, Name: 'User B' });  
  8.             $scope.EmpList.push({ Id: 3, Name: 'User C' });  
  9.             $scope.EmpList.push({ Id: 4, Name: 'User D' });  
  10.   
  11.         });  
Next, we bind the data to a html table, using the ng-repeat directive. For this, we first bind the controller to a div. and then use the ng-repeat directive on table element. So the code will look like the following: 
  1. <div ng-app="mainApp" data-ng-controller="ngRepeatController">  
  2.        <table border="1" style="width: 200px">  
  3.            <thead>  
  4.                <th>Id</th>  
  5.                <th>Name</th>   
  6.            </thead>  
  7.            <tr data-ng-repeat="Emp in EmpList">  
  8.                <td>{{ Emp.Id }}</td>  
  9.                <td>{{ Emp.Name }}</td>   
  10.            </tr>  
  11.        </table>   
  12.    </div>  
Here we have created a simple html table and applied the ng-repeat on the tr tag of the table. This acts as a for-each loop on the rows and the rows get generated, for the number of records in the EmpList array.  That's it, run the code and see the results:
 

And we are done...Happy coding...!!!
 
Read more articles on AngularJS:

Up Next
    Ebook Download
    View all
    Learn
    View all