D
D
Demigodd2018-09-20 12:17:35
Angular
Demigodd, 2018-09-20 12:17:35

How to output a value from an array to an HTML element, according to a specific pattern?

Let's say I have an array name = ['aaa', 'bbb'. 'ccc', 'ddd', 'eee'];
How to get output like this in angular using ng-repeat?

This name is aaa , bbb , ccc , ddd and eee super name.

If you write for example like this
<p>
This name <span ng-repeat="nm in name"> {{nm}}, </span> super name.
</p>

The conclusion will be like this.

This name aaa , bbb , ccc , ddd , eee , super name.

So how can you get the 1st option?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2018-09-20
@Demigodd

According to the classics, this is done by a filter, not ng-repeat. Because with ng-repeat, handling the "empty array", "array with one element" and "array with two elements" situations (an array with two elements is explained below) will look ugly in the template.
Here's what it looks like

// human-friendly-concat.js
angular.module('yourModule', [])
.filter('humanFriendlyConcat', function() {
  return function(input) {
    input = input || [];
    if (input.length === 0) {
        return 'does not exist';
    }

    if (input.length === 1) {
        return input[0];
    }

   if (input.length === 2) {
        return input.join(' and ');
    }

    return input.slice(0, -1).join(', ') + ', and ' + input.slice(-1);
  };
})

// template.html
<p>
  This name <span ng-bind="name | humanFriendlyConcat"></span>.
</p>

The difference between an array of two elements and an array of more than two elements is in the so-called "harvard comma". It comes before "and" in the enum. For example, when listing countries, we would write "Russia and Spain" for two, but "Russia, Jamaica, and Spain" for three. So it goes. https://en.wikipedia.org/wiki/Serial_comma

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question