AngularJS: a neat way to print an array as a string

I have the following array:

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

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

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

Is there a way to use filteror formatterso that I can neatly do this in a template, for example:

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

I think that writing logic for this simple analysis in the controller will clutter the body of the controller.

Thank you for your interest.

+4
source share
2 answers

This is a filter that extracts a specific support from each element of the array, then connects 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);
    };
});

Using:

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

If it is a flat array, you discard the third parameter:

<p class="authors-string">{{ animals | join:', ' }}</p>
+11

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

:

<div ng-repeat="(key, value) in myObj"> ... </div>

, :

<div ng-repeat="(key, value) in myObj"> ... <span ng-if="!$last">, </span></div>
+1

Source: https://habr.com/ru/post/1606010/


All Articles