I'm trying to use JavaScript Maps in ng-repeat angular's directive while searching I found that it could be done this way :
<ul ng-controller="MyCtrl">
<li ng-repeat='(key, value) in {"First Name":"John", "Last Name":"Smith"}'>
<span>Key: {{key}}, value: {{value}}</span>
</li>
</ul>
but this works only with normal JSON objects, when I create a real Map the following way, it doesn't work.
I have this controller for example
function MyCtrl($scope) {
$scope.items = new map();
$scope.items.set('adam',{'age':10,'fav':'doogie'});
$scope.items.set('amalie',{'age':12});
}
and this html code
<ul>
<li ng-repeat='(key, value) in items'>
<span>Key: {{key}}, value: {{value}}</span>
</li>
</ul>
this won't work because a javascript Map is an iterable object (you can loop over only through the entries iterator, calling a next() each time) and is not directly supported by angular
ng-repeat
.what you can do if you have a pre-existent code is to transform the iterable object (map) to a plain array
this will make your iterable object an array , at this point you can loop over in the standard way
working plnkr here
since
ng-repeat
not supportMap
iteration, you could use a custom filterfromMap
like belowAlthough I like Jag's answer, I've built a more extensive snippet with different implementations to achieve the same, and I took out the most of ES6 arrow functions and spread operator to implement the filter as a one-liner:
.filter('fromMap', () => mapObject => [...mapObject])
One setting a watcher and even unsuscribing to that watcher.
Here is how you can implement ng-repeat on
Map
class objects:And the corresponding Plnkr