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

我试图监视来自控制器的服务的更改。我在stackoverflow上基于许多qns尝试了各种东西,但我一直无法使它的工作。

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',myService) {


    $scope.setFTag = function() {
       myService.setFalseTag();
    };        

    $scope.$watch(function () {
       return myService.tags;
     },oldVal) {
        /*...*/
    },true);

});

演示Fiddle

[编辑]

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

为了使它工作,我们必须帮助角到消防消化循环。

这里是一个例子:

在服务端,当我们想要更新标签值写如下:

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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...