Angularjs ng-repeat error [ngRepeat:Dupes]

We all know how to use ng-repeat in Angularjs ,which will acts like loop to display N number of records in a html code. While using ng-repeat directive we will face an error [ngRepeat:Dupes].

Let’s discuss in detail how to resolve this issue, I wrote a service in codeigniter to fetch the database records, and passed to json_encode(); Which will be stored in a angular success function as below example.

var angularFormApp = angular.module('angularFormApp',[]);
angularFormApp.controller('regController',['$scope','$http',
function ($scope,$http)
{
     $scope.user = {};
    $scope.submitForm=function()
{
    $scope.registrations = {}; 
       $http({
        method:'post',
        dataType : 'json',
        url:'http://localhost:81/Codeigniter/index.php/welcome/add',
        data : $scope.user, //forms user object
        headers : {'Content-Type': 'application/json'} 
    }).success(function (data)
    {
          $scope.registrations=data;
          
    });
   
};
          
}]);

Here in the above code, json data is stored in registrations object, let’s Check the html example below how these obj reference is used in ng-repeat.

<table class="table table-hover">
                <thead>
                    <tr>
                        
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email Id</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in registrations">
                        <td>{{item.firstname}}</td>
                        <td>{{item.lastname}}</td>
                        <td>{{item.emailid}}</td>
                    </tr>
                </tbody>
            </table>

In the above code we used as

  

,so if have any duplicate in your data , Duplicate keys are banned because Angularjs uses keys to associate DOM nodes with items. You will get an error as below.

[ngRepeat:Dupes]

To resolve this issue we must use track by $index in ng-repeat and rewrite the code as below

[wp-like-lock]

<tbody>
                    <tr ng-repeat="item in registrations track by $index">
                        <td>{{item.firstname}}</td>
                        <td>{{item.lastname}}</td>
                        <td>{{item.emailid}}</td>
                    </tr>
                </tbody>

[/wp-like-lock]

By using track by $index, which will cause the items to be keyed by their position in the array instead of their value.

Thanks for reading this article

Leave a Reply