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

后端 未结 4 1986
感动是毒
感动是毒 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.

提交回复
热议问题