angular
I have a pretty basic scenario (somewhat new to angular). I am trying to convert JSON:
[
{\'name\': \'Nick\'},
{\'name\': \'David\'},
{\'name\':
Here's another approach that's more maintainable using Filters:
app.filter('commaSeparated', function () {
return function(input, property) {
var csv = '';
for (var i = 0; i < input.length; i++) {
csv += input[i][property];
if (i < input.length - 1) {
csv += ',';
}
}
return csv;
};
});
Obviously, you can replace the literal array with your $scope.menuItems...
<p>
{{ [ {'name': 'Nick'}, {'name': 'David'}, {'name': 'John'} ] | commaSeparated:'name' }}
</p>
If you are open to use <span>
instead of<p>
, then following array of objects,
[
{ "name": "John" },
{ "name": "David" },
{ "name": "Gopal" },
{ "name": "Anil" },
{ "name": "Gurjeet" }
]
can be displayed as: John, David, Gopal, Anil and Gurjeet
with this code snippet:
<span ng-repeat="admin in data">{{$first ? '' : $last ? ' and ' : ', '}}{{admin.name}}</span>
Got this solution from: AngularJS ng-repeat, comma separated with 'and' before the last item
Thanks!
One thing that would be helpful is creating a "map" filter, like so:
myModule.filter('map', function() {
return function(input, propName) {
return input.map(function(item) {
return item[propName];
});
};
});
That's the simple case of mapping to a named property, you could make it more fancy and understand dot notation, etc. Now with this, in your view you can do:
<p>
{{(menuItems | map:'name').join(',')}}
</p>
Because the map filter returns an Array, which has a built-in join method already in Javascript.
I'm not sure its possible... How to use ng-repeat without an html element
But you can always do:
<p>
<span ng-repeat="item in menuItems">{{item.name}},</span>
</p>
You cannot do this. Instead, use a map
and join
. For example:
<p>{{names}}</p>
$scope.menuItems = [
{'name': 'Nick'},
{'name': 'David'},
{'name': 'John'},
];
$scope.$watch('menuItems', function(menuItems) {
$scope.names = menuItems.map(function(item) { return item.name }).join(',');
});
This will $watch
the menuItems
and update the names
property of the $scope
whenever menuItems
changes.
I like the idea of a map filter. That's cool. For less code try this answer. Skip the name
property and the ng-repeat
and use the join() function:
<p>{{people.join(', ')}}</p>
Unfortunately, this does not work:
<p>{{people.map(function(item){return item.name;}).join(', ')}}</p>