AngularJS- 为什么我需要在 $scope.$on 内使用 $scope.$apply? [英] AngularJS- why am I needing $scope.$apply within $scope.$on?

查看:31
本文介绍了AngularJS- 为什么我需要在 $scope.$on 内使用 $scope.$apply?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
    });
});

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

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;
});

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

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.

据我所知,$scope.$on 实际上会适当地调用 $watch/$apply.那么为什么在这种情况下我需要调用 $apply 呢?

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?

该事件是由在非 angularJS 异步完成事件中调用 $rootScope.$broadcast() 触发的.

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

推荐答案

不,angular 不会在事件上触发 $apply 所以如果 $broadcast 在外面被调用angular 的上下文,您将需要手动 $apply.

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.

此处

这篇关于AngularJS- 为什么我需要在 $scope.$on 内使用 $scope.$apply?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆