AngularJS : service $broadcast and $watch not triggering on receiving controller

后端 未结 4 1984
感动是毒
感动是毒 2021-02-02 10:19

AngularJS noob here, on my path to the Angular Enlightenment :)

Here\'s the situation:

I have implemented a service \'AudioPlayer\' inside my module \'app\' and

相关标签:
4条回答
  • 2021-02-02 10:29

    As it's not safe to peek into the the digest internals, the easiest way is to use $timeout:

    $timeout(function () {
        $scope.current = track;
    }, 0);
    

    The callback is executed always in the good environment.

    EDIT: In fact, the function that should be wrapped in the apply phase is

     this.loadTrack = function(track) {
         // ... loads the track and plays it
         // broadcast 'trackLoaded' event when done
         $timeout(function() { $rootScope.$broadcast('trackLoaded', track); });
     };
    

    Otherwise the broadcast will get missed.

    ~~~~~~

    Actually, an alternative might be better (at least from a semantic point of view) and it will work equally inside or outside a digest cycle:

    $scope.$evalAsync(function (scope) {
        scope.current = track;
    });
    
    • Advantage with respect to $scope.$apply: you don't have to know whether you are in a digest cycle.
    • Advantage with respect to $timeout: you are not really wanting a timeout, and you get the simpler syntax without the extra 0 parameter.
    0 讨论(0)
  • 2021-02-02 10:36

    Tried everything, it worked for me with $rootScope.$applyAsync(function() {});

    0 讨论(0)
  • 2021-02-02 10:40

    When you have a click event the $scope is updated, without the event you'll need to use $apply

    $scope.$apply(function () {
        $scope.current = track;
    });
    
    0 讨论(0)
  • 2021-02-02 10:53
    // apply changes
    $scope.current = track;
    try {
     if (!$scope.$$phase) {
      $scope.$apply($scope.current);
     }
    } catch (err) {
     console.log(err);
    }
    
    0 讨论(0)
提交回复
热议问题