Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through JavaScript Maps using ng-repeat in angularjs?

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>
like image 636
Xsmael Avatar asked May 19 '17 14:05

Xsmael


2 Answers

since ng-repeat not support Map iteration, you could use a custom filter fromMap like below

angular.module('app', []).filter('fromMap', function() {
  return function(input) {
    var out = {};
    input.forEach((v, k) => out[k] = v);
    return out;
  };
}).controller('ctrl',function ($scope) {
    $scope.items = new Map();
    $scope.items.set('adam',{'age':10,'fav':'doogie'});
    $scope.items.set('amalie',{'age':12});
    
    $scope.logAdamAge = function() { console.log($scope.items.get("adam").age) };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div>with Map</div>
  <ul>
    <li ng-repeat="(key, value) in items | fromMap">
      <div>{{key}}</div>
      <div ng-repeat="(k, v) in value">{{k}}: <input ng-model="value[k]" /></div>
    </li>
  </ul>
  <pre>{{items | fromMap}}</pre>
  <button ng-click="logAdamAge()">log Adam age from Map</button>
</div>
like image 115
Ja9ad335h Avatar answered Sep 20 '22 08:09

Ja9ad335h


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

$scope.itemsToArray = Array.from($scope.items.entries()); 

this will make your iterable object an array , at this point you can loop over in the standard way

<ul>  
  <li ng-repeat='item in itemsToArray'>
     <span>Key: {{item[0]}}, value: {{item[1]}}</span>
  </li>
</ul>

working plnkr here

like image 45
Karim Avatar answered Sep 17 '22 08:09

Karim