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

2019-03-17 08:06发布

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.

2条回答
不美不萌又怎样
2楼-- · 2019-03-17 08:24

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

查看更多
戒情不戒烟
3楼-- · 2019-03-17 08:34

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

查看更多
登录 后发表回答