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
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;
});
$scope.$apply
: you don't have to know whether you are in a digest cycle.$timeout
: you are not really wanting a timeout, and you get the simpler syntax without the extra 0
parameter.