AngularJS trigger and watch object value change in service from controller

前端 未结 1 989
故里飘歌
故里飘歌 2020-12-13 06:17

I\'m trying to watch for changes in a service from a controller. I tried various things based on many qns here on stackoverflow, but I\'ve been unable to make it work.

1条回答
  •  渐次进展
    2020-12-13 07:18

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

    0 讨论(0)
提交回复
热议问题