使用 Angular 观察工厂变量 [英] watch factory variable with Angular

查看:22
本文介绍了使用 Angular 观察工厂变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我想查看 factory.Control 上的更改,但我无法使其正常工作.

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

当我尝试这个时:

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

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

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

推荐答案

您的语法有误.它应该返回服务变量MenuFactory.Control &最后也不需要 true ,因为您没有对象来检查对象相等性.

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

代码

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

这篇关于使用 Angular 观察工厂变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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