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:
- var app = angular.module("mainApp", []);
- app.controller('ngRepeatController', function ($scope, $http) {
-
- $scope.EmpList = [];
-
- $scope.EmpList.push({ Id: 1, Name: 'User A' });
- $scope.EmpList.push({ Id: 2, Name: 'User B' });
- $scope.EmpList.push({ Id: 3, Name: 'User C' });
- $scope.EmpList.push({ Id: 4, Name: 'User D' });
-
- });
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:
- <div ng-app="mainApp" data-ng-controller="ngRepeatController">
- <table border="1" style="width: 200px">
- <thead>
- <th>Id</th>
- <th>Name</th>
- </thead>
- <tr data-ng-repeat="Emp in EmpList">
- <td>{{ Emp.Id }}</td>
- <td>{{ Emp.Name }}</td>
- </tr>
- </table>
- </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: