Even though Deep watch has been activated in the factory, it is not triggering. What steps can be taken to resolve this issue and ensure that an event is triggered when the 'name' value changes?
Javascript Code:
var app = angular.module('app', []);
app.controller('FirstCtrl', function($scope,testFactory) {
$scope.obj = testFactory.obj;
});
app.controller('SecondCtrl',function($scope,testFactory){
$scope.obj = testFactory.obj;
$scope.valueChange = testFactory.valueChange;
});
app.factory('testFactory', ['$rootScope',function ($rootScope) {
var factory = {};
factory.obj = { 'name':'John Doe'};
$rootScope.$watch(factory.obj,function(){
alert('Value Changed');
},true);
factory.valueChange = function(){
if(factory.obj.name == 'John Doe'){
factory.obj.name = "Jane Doe";
}
else
{
factory.obj.name = "John Doe";
}
};
return factory;
}]);
Html Code:
<body >
<div ng-controller="FirstCtrl">
<h4>Value bound with FirstCtrl and factory</h4>
<input type="text" ng-model="obj.name"/>
</div>
<div ng-controller="SecondCtrl">
<br>
<br>
<h4>Value from SecondCtrl. This shows that the bind between factory and controller is working</h4>
<p>{{obj.name}}</p>
<h4>Value updated directly in the factory</h4>
<button ng-click="valueChange()">Change Value</button>
</div>
</body>
Plunker: http://plnkr.co/edit/LhHOa2NehWGVEfpHfKJQ?p=preview