Skip to content Skip to sidebar Skip to footer

Angularjs : Service $broadcast And $watch Not Triggering On Receiving Controller

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 registered like so: app

Solution 1:

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

Solution 2:

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.

Solution 3:

// apply changes$scope.current = track;
try {
 if (!$scope.$$phase) {
  $scope.$apply($scope.current);
 }
} catch (err) {
 console.log(err);
}

Solution 4:

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

Post a Comment for "Angularjs : Service $broadcast And $watch Not Triggering On Receiving Controller"