AngularJS-为什么我需要$ scope。$在$ scope内适用。$ on?

时间:2021-03-23 15:05:50

I have some code that is not behaving as expected... I have an event listener within a AngularJS controller like this:

我有一些代码没有按预期运行...我在AngularJS控制器中有一个事件监听器,如下所示:

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

控制器的标记有一个ng-show ='isReady'。当此事件处理程序运行时,ng-show区域将按预期显示。但是,此事件处理程序不起作用:

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

使用此事件处理程序,如果我使用调试器期望AngularJS范围,我确实看到$ scope.isReady = true,但是ng-show元素没有显示。

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?

据我所知,$ scope。$ on实际上会调用$ watch / $。那么为什么我需要在这种情况下拨打$ apply?

The event is being triggered by a call to $rootScope.$broadcast() within a non-angularJS asynchronous completion event.

该事件是通过在非angularJS异步完成事件中调用$ rootScope。$ broadcast()来触发的。

2 个解决方案

#1


20  

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.

不,角度不会触发$应用于事件,因此如果在角度的上下文之外调用$ broadcast,则需要手动申请$。

Check the source here

在这里检查来源

#2


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.

$ on和$ broadcast不会叫$申请,你需要自己打电话。我不确定为什么会这样,但我的猜测是因为摘要有点贵,而且为每个事件运行摘要周期都是一个成本。

#1


20  

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.

不,角度不会触发$应用于事件,因此如果在角度的上下文之外调用$ broadcast,则需要手动申请$。

Check the source here

在这里检查来源

#2


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.

$ on和$ broadcast不会叫$申请,你需要自己打电话。我不确定为什么会这样,但我的猜测是因为摘要有点贵,而且为每个事件运行摘要周期都是一个成本。