AngularJS:调用$范围在prevent错误$已经消化进度$适用()。 [英] AngularJS : Prevent error $digest already in progress when calling $scope.$apply()
问题描述
我发现我需要手动越来越多,因为在角度构建应用程序来更新我的网页我的范围。
我知道要做到这一点的唯一方法是调用 $从我的控制器和指令的适用范围()
。与此的问题是,它保持引发错误来读取控制台
错误:$已经消化进度
块引用>有谁知道如何避免这个错误或达到同样的事情,但以不同的方式?
解决方案
不要使用这个模式 - 这将最终导致更多的错误比它解决的。即使你觉得它固定的东西,它没有。
块引用>您可以检查是否
$消化
已在进行检查$范围。$$阶段
。如果(!$范围。$$阶段){
// $消化或$应用
}
$范围。$$阶段
将返回$文摘
或$申请
如果$消化
或$适用
正在进行中。我相信,这些国家之间的区别是,$摘要
将处理当前范围的手表,它的儿童和$适用
将处理所有领域的观察家。要@ dnc253的角度来看,如果你发现自己叫
$消化
或$适用
频繁,你可能会做这是错误的。总的来说,我发现我需要消化,当我需要更新范围的国家作为一个DOM事件的角度范围之外发射的结果。例如,当一个Twitter的引导模式被隐藏。有时,当一个$摘要
是前进中的DOM事件触发时,有时没有。这就是为什么我使用这个检查。我很想知道一个更好的方式,如果有人知道的。
从评论:
通过@anddoutoi
<醇开始=2>
请不要做 如果(!$范围。$$阶段)$范围。$适用()
,这意味着你的$范围。 $适用()
不在调用堆栈不够高。
块引用>I'm finding that I need to update the 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 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 it's 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
- Don't do
if (!$scope.$$phase) $scope.$apply()
, it means your$scope.$apply()
isn't high enough in the call stack.
这篇关于AngularJS:调用$范围在prevent错误$已经消化进度$适用()。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!