Skip to content Skip to sidebar Skip to footer

Ng-repeat Track By $index Display The Item Only Once If The Similar Key Exists Multiple Times In Angularjs

I was getting [ngRepeat:dupes]: error in my angularjs code. So I searched on stackoverflow and found the solution which stated to use track by $index. This is working for me now.

Solution 1:

pass array into a function and create an array without the repeating values like myFunction(users) so the repeat section will become ng-repeat="user in myFunction(users)". Write the function yourself.

Solution 2:

I fixed it like this by creating a filter:

var app = angular.module('angularTable', []);

app.filter('unique', function() {
   // we will return a function which will take in a collection// and a keynamereturnfunction(collection, keyname) {
      // we define our output and keys array;var output = [],
          keys = [];

      // we utilize angular's foreach function// this takes in our original collection and an iterator function
      angular.forEach(collection, function(item) {
          // we check to see whether our object existsvar key = item[keyname];
          // if it's not already part of our keys arrayif(keys.indexOf(key) === -1) {
              // add it to our keys array
              keys.push(key);
              // push this item to our final output array
              output.push(item);
          }
      });
      // return our array which should be devoid of// any duplicatesreturn output;
   };
});

app.controller('listdata', function($scope, $http) {

your controller logic for the users array
   });

});

In the view :

<div ng-repeat="user in users |unique:'name' | filter:myFilter track by $index">
</div>

Post a Comment for "Ng-repeat Track By $index Display The Item Only Once If The Similar Key Exists Multiple Times In Angularjs"