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
You can use $watch
instead, that seems to work. If you want to watch all the properties on the object as well (as you are doing), you need to add true
as the third parameter to the watch. This sets up a deep watch.
Here is a working plunker.
JS:
app = angular.module('myApp',[]); app.controller('MyCtrl', function($scope, $timeout){ $scope.markers = {}; $scope.$watch('markers', function(newValue, oldValue){ console.log('being watched oldValue:', oldValue, 'newValue:', newValue); }, true); $timeout( function() { $scope.markers.foo = 1; }, 500); $timeout( function() { $scope.markers.bar = 2; }, 500); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With