Firing of watch with objectequality
by cmyworld
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.js"></script>
<div ng-app ng-controller='ctrl'>
{{obj}}
{{obj1}}
</div>
JavaScript
function ctrl($scope,$timeout) {
$scope.$watch("obj", function (n, o) {
console.log("obj Data changed! ->" + JSON.stringify(n));
});
var tempObj={test:1};
$timeout(function() {$scope.obj = null;},0); //Causes watch to trigger
$timeout(function() {$scope.obj = {};},0); //Causes watch to trigger
$timeout(function() {$scope.obj = tempObj;},0); //Causes watch to trigger
$timeout(function() {$scope.obj.prop1 = "one";},0); //Does not Causes watch to trigger
$timeout(function() {$scope.obj.prop2 = "two";},0); //Does not Causes watch to trigger
$timeout(function() {$scope.obj = $scope.obj;},0); //Does not Causes watch to trigger
$scope.$watch("obj1", function (n, o) {
console.log("obj1 Data changed! ->" + JSON.stringify(n));
},true);
var tempObj1={test:2};
$timeout(function() {$scope.obj1 = null;},0); //Causes watch to trigger
$timeout(function() {$scope.obj1 = {};},0); //Causes watch to trigger
$timeout(function() {$scope.obj1 = tempObj1;},0); //Causes watch to trigger
$timeout(function() {$scope.obj1.prop1 = "one";},0); //Does Causes watch to trigger
$timeout(function() {$scope.obj1.prop2 = "two";},0); //Does Causes watch to trigger
$timeout(function() {$scope.obj1 = $scope.obj1;},0); //Does not Causes watch to trigger
}