Search code examples
javascriptangularjsangularjs-ng-repeates6-map

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>

Solution

  • 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>