angularjs $watch old value and new value are the same

Viewed 59096

My intention is to watch a model within scope, and find difference between old value and new value.

However, I found old value and new value are all the same from the following code.

app.controller('MyCtrl', function($scope, $timeout){
  $scope.markers = {};
  $scope.$watchCollection('markers', function(newValue, oldValue){
    console.log('being watched oldValue:', oldValue, 'newValue:', newValue);
  });
  $timeout( function() {
    $scope.markers.foo = 1;
  }, 500);
  $timeout( function() {
    $scope.markers.bar = 2;
  }, 500);
});

output:

being watched oldValue: Object {} newValue: Object {} script.js:6
being watched oldValue: Object {foo: 1} newValue: Object {foo: 1} script.js:6
being watched oldValue: Object {foo: 1, bar: 2} newValue: Object {foo: 1, bar: 2} 

Why are they the same, and if it's intentional, then why?

here is code, http://plnkr.co/edit/rfMCF4x6CmVVT957DPSS?p=preview

4 Answers
Related