微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;
  }

原文地址:https://www.jb51.cc/angularjs/145846.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐