AngularJS trigger and watch object value change in service from controller

[亡魂溺海] 提交于 2019-11-28 17:27:55

Try to write $watch by this way:

myApp.controller('MyCtrl', function($scope, myService) {


    $scope.setFTag = function() {
       myService.setFalseTag();
    };        

    $scope.$watch(function () {
       return myService.tags;
     },                       
      function(newVal, oldVal) {
        /*...*/
    }, true);

});

Demo Fiddle

[EDIT]

Sometimes this way will not work especially if service has been updated from 3d party.

To make it work we must help to angular to fire digest cycle.

Here is an example:

On service side when we want update tags value write something like:

if($rootScope.$root.$$phase != '$apply' && $rootScope.$root.$$phase != '$digest'){
   $rootScope.$apply(function() {
     self.tags = true;
   });
 }
 else {
   self.tags = true;
  }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!