guish guish - 6 months ago 18
Javascript Question

AngularJS : ng-repeat (return single value)

Yo everyone !

I've got :

<tr ng-repeat="x in list">
.....<td>{{x.Name}}</td>


and the view is :

a
a
a
a


For the time being, all is right.

But I would like that the table returns me the value only one time if "Name" is already present in this table. What I need is this view :

a


Because "Name" owns many "a" value.

I hope I'm accurate enough about my problem because I'm new to AngularJS.
Thank you.




EDIT1 : my controller view :
myApplicationModule.controller('controllertable', ['$scope', '$routeParams', function ($scope, $routeParams)
{
$scope.list = list;
}]);

which refers to a file .json:

var list = [
{
...
"Name" = "a",
...
}

Answer

Try this

Create the following filter

app.filter('unique', function() {
     return function(list, keyname) {
      var output = [], 
          keys = [];

      angular.forEach(list, function(item) {
          var key = item[keyname];
          if(keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(item);
          }
      });

      return output;
   };
});

And use it like

<table>
    <tr ng-repeat="x in list | unique: 'name'">
    <td>{{x.name}}</td>
  </table>
Comments