Answer the question
In order to leave comments, you need to log in
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.
<p>
This name <span ng-repeat="nm in name"> {{nm}}, </span> super name.
</p>
This name aaa , bbb , ccc , ddd , eee , super name.
Answer the question
In order to leave comments, you need to log in
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>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question