AngularJS触发器和监视对象值从控制器服务中更改

我试图从控制器中观察服务的变化。 我尝试了很多基于许多qns的东西,在stackoverflow上,但是我一直无法使它工作。

HTML:

<div ng-app="myApp"> <div ng-controller="MyCtrl"> <div ng-click="setFTag()">Click Me</div> </div> </div> 

JavaScript的:

 var myApp = angular.module('myApp',[]); myApp.service('myService', function() { this.tags = { a: true, b: true }; this.setFalseTag = function() { alert("Within myService->setFalseTag"); this.tags.a = false; this.tags.b = false; //how do I get the watch in MyCtrl to be triggered? }; }); myApp.controller('MyCtrl', function($scope, myService) { $scope.setFTag = function() { alert("Within MyCtrl->setFTag"); myService.setFalseTag(); }; $scope.$watch(myService.tags, function(newVal, oldVal) { alert("Inside watch"); console.log(newVal); console.log(oldVal); }, true); }); 

如何让手表在控制器中触发?

的jsfiddle

尝试通过这种方式写$watch

 myApp.controller('MyCtrl', function($scope, myService) { $scope.setFTag = function() { myService.setFalseTag(); }; $scope.$watch(function () { return myService.tags; }, function(newVal, oldVal) { /*...*/ }, true); }); 

演示小提琴

[编辑]

有时这种方式将不会工作,特别是如果服务已经从三方更新。

为了使其工作,我们必须帮助消除消化周期。

这里是一个例子:

在服务端,当我们想要更新tags值时,写下如下内容:

 if($rootScope.$root.$$phase != '$apply' && $rootScope.$root.$$phase != '$digest'){ $rootScope.$apply(function() { self.tags = true; }); } else { self.tags = true; }