Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Neat way to print array as string

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.

like image 279
abdul-wahab Avatar asked Sep 04 '15 21:09

abdul-wahab


2 Answers

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 (!angular.isUndefined(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>
like image 118
Ori Drori Avatar answered Sep 19 '22 05:09

Ori Drori


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>

To add a comma on all but the last value:

<div ng-repeat="(key, value) in myObj"> ... <span ng-if="!$last">, </span></div>
like image 26
eSs Avatar answered Sep 22 '22 05:09

eSs