even after activating deep watch in factory not triggering. how solve issue event can triggered on 'name' value change?
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 firstctrl , factory</h4> <input type="text" ng-model="obj.name"/> </div> <div ng-controller="secondctrl"> <br> <br> <h4>value secondctrl. shows bind between factory , controller working</h4> <p>{{obj.name}}</p> <h4>value updated directly in factory</h4> <button ng-click="valuechange()">change value</button> </div> </body>
plunker: http://plnkr.co/edit/lhhoa2nehwgvefphfkjq?p=preview
try way:
$rootscope.$watch(function () { return factory.obj; }, function(){ alert('value changed'); }, true);
better solution watch changes in controller instead of factory:
app.controller('secondctrl',function($scope,testfactory){ $scope.obj = testfactory.obj; $scope.valuechange = testfactory.valuechange; $scope.$watch('obj', function () { alert('value changed'); }, true); });
in case $scope.obj
, testfactory.obj
points same object in memory. no matter 1 watch for.
Comments
Post a Comment