1

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 {{}}

1
  • your question isn't exactly clear. yes, you would use ng-repeat, and limitTo works perfectly fine in an ng-repeat. Commented Jul 18, 2015 at 21:22

2 Answers 2

3

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}}
Sign up to request clarification or add additional context in comments.

3 Comments

Simplest solution(s) for including the commas
Would {{ctrl.items | names | limitTo: 2}} be valid?
you should use limitTo filter before names filter so it would be like this {{ctrl.items | limitTo: 2 | names}}
1

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.

1 Comment

How would you implement the commas in between each item? Without a comma after the last item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.