0

Whenever I try to bind a Map to the scope, it is replaced with an empty object during the digest cycle. Can anyone explain why this is happening?

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.testMap = new Map();
    $scope.testMap.set("testKey", "testValue");
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <pre>{{testMap}}</pre>
</div>
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
Ryan Helmoski
  • 359
  • 2
  • 7
  • It not gets replaced, it's only rendered this way. You can still use it, however I think change detection does not work on sets and maps. – Tamas Hegedus Feb 19 '16 at 18:51
  • Are you sure the `Map` is being replaced with an empty object? There's nothing magical happening in the code you've shown. Maybe the problem is that how Angular evaluates the expression `{{testMap}}`? Have you tried `{{testMap | json}}` or `{{testMap.get('testKey')}}`? – Sunil D. Feb 19 '16 at 18:53

1 Answers1

3

Transforming a Map to JSON is not supported (or, to be precise, the entries of the map are not serialized as if they were the fields of a regular object).

So Angular can't display the content of the map (the json filter is implicitly used when displaying an object using {{ testMap }}.

Demonstration: http://plnkr.co/edit/AjJWNGXZLR5KhhJ8cz0g?p=preview

Related: How do you JSON.stringify an ES6 Map?

Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255