从控制器服务AngularJS触发和观察对象价值变动 [英] AngularJS trigger and watch object value change in service from controller

查看:122
本文介绍了从控制器服务AngularJS触发和观察对象价值变动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图观看从控制器在服务的变化。我试图基于各种事情很多QNS这里计算器,但我一直无法使其工作。

I'm trying to watch for changes in a service from a controller. I tried various things based on many qns here on stackoverflow, but I've been unable to make it work.

HTML

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

JavaScript的:

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

});

我如何拿到手表在控制器触发?

How do I get the watch to trigger in the Controller?

的jsfiddle

推荐答案

试着写 $观看通过这样的方式:

Try to write $watch by this way:

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


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

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

});

演示<大骨节病> 小提琴

有时,这样就不会特别是工作,如果服务已经从政党3D更新。

Sometimes this way will not work especially if service has been updated from 3d party.

要使它发挥作用,我们必须的帮助的角度来火消化周期。

To make it work we must help to angular to fire digest cycle.

下面是一个例子:

在服务端的时候,我们要更新标记值写是这样的:

On service side when we want update tags value write something like:

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

这篇关于从控制器服务AngularJS触发和观察对象价值变动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆