Xsmael Xsmael -4 years ago 107
AngularJS Question

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>

but this works only with normal JSON objects, when i create a real Map the following way, it doesn't work.

if i have this controller for example.

function MyCtrl($scope) {
$scope.items = new map();

and this html code

<li ng-repeat='(key, value) in items'>
<span>Key: {{key}}, value: {{value}}</span>

Answer Source

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.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>
    <li ng-repeat="(key, value) in items | fromMap">
      <div ng-repeat="(k, v) in value">{{k}}: <input ng-model="value[k]" /></div>
  <pre>{{items | fromMap}}</pre>
  <button ng-click="logAdamAge()">log Adam age from Map</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download