AngularJS从控制器触发并观察服务中的对象值变化



我正在尝试从控制器监视服务中的更改。 我在堆栈溢出上尝试了基于许多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);
});

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

斯菲德尔

尝试用这种方式编写$watch

myApp.controller('MyCtrl', function($scope, myService) {

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

演示小提琴

[编辑]

有时这种方式将不起作用,尤其是在服务已从 3d 方更新的情况下。

为了使它起作用,我们必须帮助角度到火的消化循环。

下面是一个示例:

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

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

最新更新