I have some code that is not behaving as expected... I have an event listener within a AngularJS controller like this:
$scope.$on("newClipSelected", function(e) {
$scope.$apply(function() {
$scope.isReady = true;
});
});
The controller's markup has a ng-show='isReady'. When this event handler runs, the ng-show region shows as expected. However, this event handler does not work:
$scope.$on("newClipSelected", function(e) {
$scope.isReady = true;
});
With this event handler, if I use the debugger to expect the AngularJS scope I do see that $scope.isReady=true, however the ng-show element is not showing.
Its my understanding that $scope.$on will in fact call $watch/$apply as appropriate. So why am I needing to call $apply in this case?
The event is being triggered by a call to $rootScope.$broadcast() within a non-angularJS asynchronous completion event.
No, angular doesn't fire
$apply
on the events so if$broadcast
is called outside angular's context, you are going to need to$apply
by hand.Check the source here
$on
and$broadcast
doesn't call$apply
for you, you need to call it yourself. I'm not sure why that is, but my guess is that it's because a digest is a bit expensive, and it would be a cost to run a digest cycle for every event.