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
You need to pass true as the last parameter of the $watch function so that the equality check is angular.equals. Otherwise only reference equality is checked.
$scope.$watch('test.getData()', function(newVal){
console.log('data changes into: ', newVal)
}, true);
Duplicate question: $watch an object
EDIT
As mentioned bellow, the code includes a bad practice – having a service referenced in $scope
. It is not necessary to reference it in scope, since $watch
also accepts a getter function as first argument. Clean solution uses this function to return the watched array as is in the answer below.
$scope.$watch(function() { return test.getData(); } ...
To list a complete solution you could also use $watchCollection
instead to solve the reference equality check problem.