0

I have a service (Utilities) that returns a promise object:

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

});

In my controller I call the promise object when it's ready, which works...

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

...but I'm trying to "watch" for when self.filteredDataGlobal changes on the Utilities service. Right now this is logging undefined, undefined

Rob
  • 14,746
  • 28
  • 47
  • 65
NewToJS
  • 2,011
  • 4
  • 35
  • 62
  • good post here: [http://stackoverflow.com/questions/12576798/angularjs-how-to-watch-service-variables](http://stackoverflow.com/questions/12576798/angularjs-how-to-watch-service-variables) – jjwilly16 Aug 09 '16 at 03:19
  • Use $broadcast. Here is answer to your question http://stackoverflow.com/a/20863597/2003481 – kraken Aug 09 '16 at 03:22

1 Answers1

0

$scope.$watch only watches variables on your scope. You saved that variable in the context of utility not scope. Maybe pass scope in and store the global value on scope so you can watch it? Or have a setter that gets called and you can emit an event?

MorningDew
  • 503
  • 3
  • 9