Angularjs watch service object

Robin Timman picture Robin Timman · Nov 7, 2014 · Viewed 18.3k times · Source

Why can't I watch a object in a service. Ive got a simple variable working, but a object wont work. http://plnkr.co/edit/S4b2g3baS7dwQt3t8XEK?p=preview

var app = angular.module('plunker', []);

app.service('test', ['$http', '$rootScope',
            function ($http,   $rootScope) {

  var data = 0;
  var obj  = {
                "data": 0
              };

  this.add = function(){
    obj.data += 1;
    console.log('data:', obj);
  };

  this.getData     = function() { return obj; };

}]);

app.controller('TestController', ['$scope', '$rootScope', '$filter', 'test',
                          function($scope,   $rootScope,   $filter,   test) {

  //test controller
  $scope.add = function(){
    test.add();
  };
  $scope.test = test;
  $scope.$watch('test.getData()', function(newVal){
    console.log('data changes into: ', newVal)
  });
}]);

Answer

Pierre Gayvallet picture Pierre Gayvallet · Nov 7, 2014

injecting whole services into a scope is not something I would do.

I would prefer to watch a function returning the value :

$scope.$watch(function() { return test.getData(); }, function(newVal) { 
    /* Do the stuff */
}, true);