Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs $watch old value and new value are the same

Tags:

angularjs

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

like image 502
allenhwkim Avatar asked Dec 23 '13 22:12

allenhwkim


1 Answers

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); }); 
like image 169
Davin Tryon Avatar answered Sep 28 '22 07:09

Davin Tryon