Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma Separated <p> angular

Tags:

angularjs

I have a pretty basic scenario (somewhat new to angular). I am trying to convert JSON:

[
    {'name': 'Nick'},
    {'name': 'David'},
    {'name': 'John'},
]

To:

<p>Nick,David,John</p>

But I can not figure out how to generate a single "p." How do you call ng-repeat inside of the <p>

<p ng-repeat="item in menuItems">{{item.name}}</p>
like image 559
Nix Avatar asked May 21 '13 15:05

Nix


2 Answers

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.

like image 59
jpsimons Avatar answered Oct 20 '22 08:10

jpsimons


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.

like image 21
Matt York Avatar answered Oct 20 '22 08:10

Matt York