Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I have a following array:

"cast": [
      {
        "name": "James Stewart"
      },
      {
        "name": "Kim Novak"
      },
      {
        "name": "Barbara Bel Geddes"
      },
      {
        "name": "Tom Helmore"
      }
    ]

What is the neat in AngularJS to to format it as:

James Stewart, Kim Novak, Barbara Bel Geddes, Tom Helmore

Is there a way to use filter or formatter so that I can neatly do it in template like:

<font class="authors-string">{{ object.cast | filter/formatter/? }}</font>

I think writing logic for this simple parsing in controller would clutter controller body.

Thanks for your interest.

share|improve this question
2  
Just use ng-repeat: <div ng-repeat="person in cast">{{ person.name }}</div> edit: <span> might be better for you here –  azium Sep 4 at 21:35
    
does ng-repeat not work? –  Claies Sep 4 at 21:35
    
For ng-repeat, how will I join the strings by comma? –  abdul-wahab Sep 4 at 22:30

2 Answers 2

up vote 3 down vote accepted

This is a filter that extracts a certain prop from each array element, then joins them using a separator (demo):

app.filter('join', function () {
    return function join(array, separator, prop) {
        if (!Array.isArray(array)) {
            return array; // if not array return original - can also throw error
        }

        return (!!prop ? array.map(function (item) {
            return item[prop];
        }) : array).join(separator);
    };
});

Usage:

<p class="authors-string">{{ cast | join:', ':'name' }}</p>

If it is a flat array, you drop the 3rd parameter:

<p class="authors-string">{{ animals | join:', ' }}</p>
share|improve this answer
    
Thanks, it simplified my code. But are there any dangers associated with using Array.prototype.map regarding compatibility? –  abdul-wahab Sep 4 at 22:27
    
It works for IE9 and all modern browsers. –  Ori Drori Sep 4 at 22:34

You can use 'ng-repeat' - https://docs.angularjs.org/api/ng/directive/ngRepeat

An example would be:

<div ng-repeat="(key, value) in myObj"> ... </div>
share|improve this answer
    
But how I'll insert joining commas in between items if I use ng-repeat? –  abdul-wahab Sep 4 at 22:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.