AngularJS从控制器触发并监视对象值的服务变化

 泰有趣 发布于 2023-02-09 13:10

我正试图从控制器中观察服务的变化.我在stackoverflow上尝试了很多基于很多qns的东西,但我一直无法使它工作.

HTML:

Click Me

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

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

    2023-02-09 13:14 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有