-1

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. But, it displays the item multiple times if the same key is present multiple times. I want to display only one item if the same key exists multiple times. here is my sample code from the view :

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

here is the current output : enter image description here

Insted of showing these two cards, I want the code to show only one card as they both are the same. How do I do it?

node_man
  • 1,359
  • 4
  • 23
  • 50

2 Answers2

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.

Golwin
  • 161
  • 13
  • please take a look at my question [here](https://stackoverflow.com/questions/55591159/optimise-ng-bind-directive-in-angularjs) – node_man Apr 09 '19 at 11:14
0

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 keyname
   return function(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 exists
          var key = item[keyname];
          // if it's not already part of our keys array
          if(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 duplicates
      return 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>
node_man
  • 1,359
  • 4
  • 23
  • 50
  • 1
    its better to use function than filter because filter will get called multiple times but function does not. See my answer. – Golwin Nov 28 '18 at 09:01