Sherman Szeto
Sherman Szeto

Reputation: 2405

How to iterate over object array in angular but display only property with {{}}?

Suppose we have an object array:

    var items = [
  {
    id: 1,
    name: 'name1'
  }, {
    id: 2,
    name: 'name2'
  },
  {
    id: 3,
    name: 'name3'
  }
];

and we want to iterate over it in HTML using this:

{{ctrl.items}}

expecting this in the UI:

name1, name2, name3

Is this possible? Or do I have to use a ngRepeat for that?

I want to mainly do this to take advantage of the limitTo filter inside the {{}}

Upvotes: 1

Views: 52

Answers (2)

Ahmed Eid
Ahmed Eid

Reputation: 1183

you can use code like this in your HTML

{{ctrl.getNames(ctrl.items)}}

and in your controller add this function

this.getNames = function(items){
     return items.map(function(item){return item.name;}).join(", ");
}

or you can make a filter for this ,,

app.filter("names",function(){
   return function(input){
      return input.map(function(item){return item.name;}).join(", ");
   };
});

and in your HTML use this

{{ctrl.items | names}}

Upvotes: 3

Daniel Cottone
Daniel Cottone

Reputation: 4480

You can accomplish this by using both ng-repeat and the limitTo filter:

<div ng-repeat="item in items | limitTo: 3">{{ item.name }}</div>

EDIT:

Here is a working plunkr.

Upvotes: 1

Related Questions