Angularjs watch service object

浪子不回头ぞ 提交于 2019-12-02 23:37:34
kvetis

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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!