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 th
This is a bug.
https://github.com/angular/angular.js/issues/2621
and it seems not being fixed.
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);
});
The values are passed as parameters
$scope.$watch('foo', function (newValue, oldValue) {
// ...
}
I found that it's very useful to check if the new and old value are equal (in values) and skip the process if that's the case to avoid unexpected behavior. You can use angular.equals to achieve that. Here's an example:
JS:
$scope.$watch('myObject', function(newValue, oldValue){
if(angular.equals(newValue, oldValue)){
return; // simply skip that
}
});