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.Tried everything, it worked for me with $rootScope.$applyAsync(function() {});
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;
});
// apply changes
$scope.current = track;
try {
if (!$scope.$$phase) {
$scope.$apply($scope.current);
}
} catch (err) {
console.log(err);
}