【问题标题】:AngularJS trigger and watch object value change in service from controllerAngularJS 从控制器触发并观察服务中的对象值变化
【发布时间】:2014-01-07 04:22:05
【问题描述】:

我正在尝试从控制器观察服务的变化。我在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);

});

如何让手表在 Controller 中触发?

jsfiddle

【问题讨论】:

  • 在问题here 中查看我的答案。 watch 函数中的语法不是您想要的,但它仍然是有效的角度语法,这就是您没有收到日志错误的原因。

标签: angularjs watch


【解决方案1】:

尝试这样写$watch

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


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

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

});

演示Fiddle

[编辑]

这种方式有时行不通,尤其是当服务已从 3d 方更新时。

为了让它发挥作用,我们必须帮助从角度来触发摘要循环。

这是一个例子:

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

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

【讨论】:

  • 我不知道你可以这样使用手表。这是一个游戏规则改变者。赢了这么多。
  • 对我来说这种方式更好,因为可以避免变量的拼写错误。
  • @Phill 我只添加了其他测试用例:例如,如果您使用超出角度范围的 Cordova 插件,则观察程序不起作用。人们可能会复制/粘贴此示例,并且会惊讶为什么它不起作用。所以我尝试涵盖不同的情况
  • 你能解释一下为什么我们必须使用返回函数吗?它工作得很好,但我真的不明白。
  • 为什么服务中没有return语句?它是如何工作的?
猜你喜欢
  • 2015-10-01
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
  • 2015-12-27
  • 2015-08-20
  • 1970-01-01
  • 2015-11-06
  • 1970-01-01
相关资源
最近更新 更多