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>

2
  • 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. Commented Feb 19, 2016 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')}}? Commented Feb 19, 2016 at 18:53

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.