最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - watch factory variable with Angular - Stack Overflow

programmeradmin0浏览0评论

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

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

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 ?

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

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

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 ?

Share Improve this question edited Sep 20, 2016 at 20:09 Pankaj Parkar 136k23 gold badges240 silver badges303 bronze badges asked Jun 2, 2015 at 12:35 PierolainPierolain 1891 gold badge3 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

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.

Code

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

评论列表(0)

  1. 暂无评论