In Focus

ng-repeat In AngularJS

In this article, you will learn about ng-repeat in AngularJS.

The ng-repeat is a directive which is used to repeat or to generate a tag (or) element multiple times (based on the count of our array size or collection).


This is will be similar to the foreach loop which loops throughout the whole collection.

  1. <tag ng-repeat=”item in collection ”>  
  2. //we can use “item” to get the value from collection each time it loops. As like {{ item }}  
  3. </tag>  
This syntax that we have needs to attach to any of the elements wherever we require the collection of items need to be placed.

For example, we have a collection of items which need to display as a list tag(<li> )format. In that case, we need to attach the ng-repeat directive to that preferred or required tag .

Let’s see an example.
  1. <div ng-app="">      
  2.         <ol>  
  3.             <li ng-repeat="item in ['Ramu','Dinesh','Sreekanth','Hari']">  
  4.                 {{item}}  
  5.             </li>  
  6.         </ol>  
  7.     </div  
In the example, mentioned above, we can see the implementation of ng-repeat, which was applied to the element <li>, as shown below. 
  1. “<li ng-repeat="item in ['Ramu','Dinesh','Sreekanth','Hari']">”.  
Here, if we try to access the “item” in our tag, we can get the element or tag, which is present in the collection, which we had through the expression {{ item }}.

This means our code is going to generate a <li> tag multiple times,  which equals the count of the collection which we provided (in our code collection,  it is nothing but the array we used).

Scope of ng-repeat

ng-repeat items can be used only within the scope, where we create ng-repeat directive.

We cannot access the variables of ng-repeat outside the ng-repeat directive.

The code, mentioned above will result as shown below.

Duplicates in ng-repeat

Now, let me discuss what happens if the set or collection of items is having some duplicate values? How is the Angular going to treat the duplicate values in a collection?
  1. <div ng-app="">  
  3.         <ol>  
  4.             <li ng-repeat="item in ['Ramu','Ramu','Sreekanth','Hari']">  
  5.                 {{item}}  
  6.             </li>  
  7.         </ol>  
  9.     </div>   
In the code, mentioned above, in li tag, we can see the ng-repeat attribute with an array having the elements. In the elements list, we can find that the item ‘Ramu’ was there more than one time.

In this case, the Angular library won’t provide any result. If we try to execute with duplicates in our collection, we will not get any result related to the collection. We can observe the error in console log, as shown below.

Clearly from the console we can find the error log saying: “Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in ['Ramu','Ramu','Sreekanth','Hari'], Duplicate key: string:Ramu, Duplicate value: Ramu”.

If we understand what the  error log says, we can find a new word, “track by,” which error log asks us to use to overcome this error.

Using “track by” to overcome duplication problem

Here “track by” is the word, which is used to track the iteration based on the item, which we provide followed by it.

Ex track by empno

In the example, mentioned above, our ‘track by’ was followed by ‘empno’ so, here empno must be unique like primary key.

If we take our previous li tag, we can generate it with duplicates in ng-repeat, as shown below.
  1. <div ng-app="">  
  3.         <ol>  
  4.             <li ng-repeat="item in ['Ramu','Ramu','Sreekanth','Hari'] track by $index">  
  5.                 {{item}}  
  6.             </li>  
  7.         </ol>  
  9.     </div>  
In the code, mentioned above, the “track by” is followed by ‘$index’.

Now, the line makes you think, what is $index? From our above discussion, track by will be followed by unique item or column. We can be clear that $index also would be like a unique one. This $index will generate the iteration count number. As the iteration count will be always incremented, we can make it to be after “track by” and it makes our result to be as we expected according to our array.

Here, without any doubt, instead of $index, we can have our unique ID for tracking purpose.

For example, in my model, If I’m having an employee object with different properties which are distinguished by EmpId (Employee ID), I can make “track by employee.EmpId”.

Filter in ng-repeat

From the list of large data in a table, we can filter the data based on the user input. Commonly this type of scenario makes us write very vast code. As our AngularJS is a two way databinder here, our code becomes shorthand and also flexible.

As a technical point of view, we can say that the filter option, which we use in ng-repeat, will return a subset of the whole data according to the user input from the whole collection which is available.

Example for filter in ng-repeat
  1. <html xmlns="">  
  2. <head runat="server">  
  3.     <title></title>  
  4.     <script src="Scripts/angular.js"></script>  
  5.     <script>  
  6.    var app = angular  
  7.             .module("itsmodule", [])  
  8.             .controller("itscontroller"function ($scope) {  
  9.                 var employees=  
  10.                     [  
  11.                         {name:'Hari',gender:'Male',salary:50000,city:'Hyd'},  
  12.                         { name: 'Ravi', gender: 'Male', salary: 60000, city:'Banglore' },  
  13.                         { name: 'Ram', gender: 'Male', salary: 70000, city: 'Chennai' },  
  14.                         { name: 'Sreekanth', gender: 'Male', salary: 80000,city:'Pune' },  
  15.                         { name: 'Dinesh', gender: 'Male', salary: 90000, city: 'Hyd' },  
  16.                         { name: 'swapna', gender: 'Female', salary: 50000,city:'London' }  
  17.                     ]  
  18.                 $scope.employees = employees;  
  19.                 $scope.hai = "hai";  
  20.             });  
  21.         </script>  
  22. </head>  
  23. <body>  
  24.     <form id="form1" runat="server">  
  25.     <div ng-app="itsmodule">  
  26.         <div ng-controller="itscontroller">  
  27.   Search key : <input type="text" id="txtsearch" ng-model="searchWord" />  
  28.        <table>  
  29.            <thead>  
  30.                <tr>  
  31.                    <th>Name</th>  
  32.                    <th>Gender</th>  
  33.                    <th>Salary</th>  
  34.                    <th>City</th>  
  35.                </tr>  
  36.            </thead>  
  37.            <tbody>  
  38.                <tr ng-repeat="emp in employees | filter : searchWord">  
  39.                    <td>{{}}</td>  
  40.                    <td>{{emp.gender}}</td>  
  41.                    <td>{{emp.salary}}</td>  
  42.                    <td>{{}}</td>  
  43.                </tr>  
  44.            </tbody>  
  45.        </table>  
  46. </div>  
  47.     </div>  
  48.     </form>  
  49. </body>  
  50. </html>  
From the code, mentioned above, we can observe the ng-repeat with filter option. We can find the keyword “filter : searchword”. Searchword is a model variable, which stores the user search item from the text box. The feature two way databinding will automatically look over the table as the user enters his search word in the text box and immediately we can find the table items or the content, which is filtered.