javascript 使用 Angular 观察工厂变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30596258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:24:32  来源:igfitidea点击:

watch factory variable with Angular

javascriptangularjsangularjs-scopeangularjs-factoryangularjs-watch

提问by Pierolain

My single page application has 2 controllers : the first is for my main menu and the second is for the view. They share data with this factory

我的单页应用程序有 2 个控制器:第一个用于我的主菜单,第二个用于视图。他们与这家工厂共享数据

myApp.factory('MenuFactory', function(){
var factory = {
    Monitor: "doneJob",
    Control: "",
    Report: "",
    Display: "",
    setMonitor: function(value){
        factory.Monitor = value;
    },
    setControl: function(value){
        factory.Control = value;
    },
    setReport: function(value){
        factory.Report = value;
    },
    setDisplay: function(value){
        factory.Display = value;
    }

};
return factory;
});

I would like to watch change on factory.Control, but i can't make it works.

我想在 上观看更改factory.Control,但我无法使其正常工作。

When i try this:

当我尝试这个时:

$scope.$watch(function(){MenuFactory.Control}, function(NewValue, OldValue){
    console.log(NewValue + ' ' + OldValue);
    console.log(MenuFactory.Control);
}, true);

I get "undefined undefined" and "Process" in console. Is there any problem with my $watch implementation for this factory ?

我在控制台中得到“undefined undefined”和“Process”。这个工厂的 $watch 实现有什么问题吗?

回答by Pankaj Parkar

You had a wrong syntax. It should returnthe service variable MenuFactory.Control& also there is no need of truein the end as you don't have object to check object equality.

你的语法错误。它应该return是服务变量MenuFactory.Control,并且最终也不需要,true因为您没有对象来检查对象相等性。

Code

代码

$scope.$watch(function(){
   return MenuFactory.Control;
}, function(newValue, oldValue){
    console.log(newValue + ' ' + oldValue);
    console.log(MenuFactory.Control);
});