AngularJS- why am I needing $scope.$apply within $scope.$on?

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Method 2

$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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply