2016-08-09 33 views
0

我有一個返回一個承諾對象服務(公用):

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

}); 

在我控制我所說的承諾對象時,它的準備,其中工程..

.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何時更改實用程序服務。現在這是日誌記錄undefined,undefined

+0

好帖子在這裏:[http://stackoverflow.com/questions/12576798/angularjs-how-to-watch-service-variables](http://stackoverflow.com/questions/12576798/angularjs-how-to -watch-service-variables) – jjwilly16

+0

使用$ broadcast。這裏回答你的問題http://stackoverflow.com/a/20863597/2003481 – kraken

回答

0

$ scope。$ watch只監視您的範圍的變量。您將該變量保存在實用程序而非範圍的上下文中。也許可以傳入範圍並將全局值存儲在範圍中,以便您可以觀看它?或者有一個被調用的setter,你可以發出一個事件?