ng-repeat

Ng-repeat is one of the directive in angularjs. It is used to looping the given object or array. When we need to display the set of html in repeated mode with some data or collection then we can use ng-repeat directive.


ng-repeat example

In my previous controller example, I have return object of course with course name and fees. In this example I want to return the multiple object of course and name and want to display in tabular format. So we need to create multiple rows i.e. tr correspond data. So we will use ng-repeat in following manner


<!doctype html>
<html lang="en">
<head>
    <title>Angularjs Repeat</title>
    <meta charset="UTF-8">
  
</head>
<body data-ng-app="mymodule"> 
    <div ng-controller="courses">
     <table border="1">
        <tr>
            <td>Course Name</td> <td>Course Fees</td>
            </tr>
            <tr ng-repeat="x in data">
            <td> {{x.name}} </td>
                 <td> {{x.fees}} </td>
            </tr>
        </table>
    </div>
<script src="angular.js"></script>
    <script>
    
        var p= angular.module('mymodule',[]).controller('courses',function($scope)
                                                       {
           var result=[
               {
                   name:'Asp.net', fees:'15000'
               },
               {
                   name:'php', fees:'17000'
               },
               {
                   name:'AngularJS', fees:'8000'
               }
           ] ;
           
           $scope.data=result;
        });
    </script>
</body>
</html>

As you can see that we have used ng-repeat at tr tag as we want to repeat tr tag accruing to data returned by the controller. ng-repeat syntax is almost similar to foreach loop.

Now execute the program and you will get following output

		
		what is ng-repeat
		Figure 1
		
		

Ng-repeat with track by

Let us take another example. Suppose we have following index array with repeating records:-

		
		<script>
    var x=angular.module("module1",[]);
        x.controller("con1",function($scope){
                    
            $scope.result=[2,4,4,4,5,6,7];
        });
        
    </script>
		
		

Now traverse this array using ng-repeat and you will get following error:-

		
		ng-repeat with track by $index
		Figure 2
		
		

To traverse duplicate records in ng-repeat we will use $index in the following code:-

		
		<body ng-app="module1">
    <div ng-controller="con1">
            <div ng-repeat="k in result track by $index">
            <p>{{k}}</p>
                </div>
    </div>
    </body>
		
		

In my next article we will see more example of ng-repeat with ng-init.