AngularJS:在调用 $scope.$apply() 时防止错误 $digest 已经在进行中 [英] AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

查看:33
本文介绍了AngularJS:在调用 $scope.$apply() 时防止错误 $digest 已经在进行中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自从以 angular 构建应用程序以来,我越来越需要手动将页面更新到我的范围.

我所知道的唯一方法是从我的控制器和指令的范围内调用 $apply().这样做的问题是它不断向控制台抛出一个错误:

<块引用>

错误:$digest 已在进行中

有谁知道如何避免此错误或以不同的方式实现相同的目标?

解决方案

不要使用这种模式 - 这最终会导致比解决的错误更多.即使你认为它修复了某些东西,它也没有.

您可以通过检查 $scope.$$phase 来检查 $digest 是否已经在进行中.

if(!$scope.$$phase) {//$digest 或 $apply}

$scope.$$phase 将返回 "$digest""$apply" 如果 $digest$apply 正在进行中.我相信这些状态之间的区别在于 $digest 将处理当前作用域及其子作用域的观察者,而 $apply 将处理所有作用域的观察者.>

对于@dnc253 的观点,如果您发现自己经常调用$digest$apply,那么您可能做错了.我通常发现当我需要更新范围的状态时,我需要消化,因为 DOM 事件在 Angular 的范围之外触发​​.例如,当 Twitter 引导模式变为隐藏时.有时 DOM 事件会在 $digest 正在进行时触发,有时不会.这就是我使用这张支票的原因.

如果有人知道,我很想知道一种更好的方法.

<小时>

来自评论:来自@anddoutoi

angular.js 反模式

<块引用>

  1. 不要做 if (!$scope.$$phase) $scope.$apply(),这意味着你的 $scope.$apply()在调用堆栈中不够高.

I'm finding that I need to update my page to my scope manually more and more since building an application in angular.

The only way I know of to do this is to call $apply() from the scope of my controllers and directives. The problem with this is that it keeps throwing an error to the console that reads :

Error: $digest already in progress

Does anyone know how to avoid this error or achieve the same thing but in a different way?

解决方案

Don't use this pattern - This will end up causing more errors than it solves. Even though you think it fixed something, it didn't.

You can check if a $digest is already in progress by checking $scope.$$phase.

if(!$scope.$$phase) {
  //$digest or $apply
}

$scope.$$phase will return "$digest" or "$apply" if a $digest or $apply is in progress. I believe the difference between these states is that $digest will process the watches of the current scope and its children, and $apply will process the watchers of all scopes.

To @dnc253's point, if you find yourself calling $digest or $apply frequently, you may be doing it wrong. I generally find I need to digest when I need to update the scope's state as a result of a DOM event firing outside the reach of Angular. For example, when a twitter bootstrap modal becomes hidden. Sometimes the DOM event fires when a $digest is in progress, sometimes not. That's why I use this check.

I would love to know a better way if anyone knows one.


From comments: by @anddoutoi

angular.js Anti Patterns

  1. Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack.

这篇关于AngularJS:在调用 $scope.$apply() 时防止错误 $digest 已经在进行中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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