试图$观察服务变量的变化

时间:2016-08-09 03:10:02

标签: javascript angularjs

我有一个返回promise对象的服务(Utilities):

.service('Utilities',function($q){

    var self = this;
    var deferred = $q.defer();

    ..... function thats calls self.filteredDataGlobal.....

    self.getFilteredData = function(){
        if(self.filteredDataGlobal){
            deferred.resolve(self.filteredDataGlobal);
        }
        return deferred.promise;
    };

});

在我的控制器中,当它准备好时,我会调用promise对象,这有效...

.controller('myController', function($scope, Utilities) {

   var self = this;

    Utilities.getFilteredData().then(function(data){
        self.filteredData = data;
    });

    //watch for when self.filteredDataGlobal changes on the Utilities service
    $scope.$watch(self.filteredData, function (newVal, oldVal) {
        console.log(newVal, oldVal);
        self.filteredData = newVal;
    });
});

...但我正试图观看"当self.filteredDataGlobal在Utilities服务上更改时。现在这是记录undefined,undefined

1 个答案:

答案 0 :(得分:0)

$ scope。$ watch仅监视您范围内的变量。您在实用程序而非范围的上下文中保存了该变量。也许通过范围并将全局值存储在范围内,以便您可以观看它?或者有一个被调用的setter,你可以发出一个事件?