What is ng-repeat

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

Example of ng-repeat

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>
    <title>Untitled Document</title>
    <meta charset="UTF-8">
<body ng-app="mymodule">
    <div ng-controller="courses">
     <table border="1">
            <td>Course Name</td> <td>Course Fees</td>
            <tr ng-repeat="x in data">
            <td> {{x.name}} </td>
                 <td> {{x.fees}} </td>
     <script src="angular.js"></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'
           ] ;


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:-

    var x=angular.module("module1",[]);

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">

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