问题描述
$apply
函数可以在任何范围内运行,包括 $rootScope
.
The $apply
function can run on any scope, including $rootScope
.
如果我在本地范围内运行它或在我的 $rootScope
上运行它,是否会产生不同的情况?
Are there cases when it makes a difference if I run it on my local scope or if I run it on my $rootScope
?
我之所以这么问是因为我想创建一个辅助函数,将给定的函数包装在 $apply
中.为此,我总是需要传入一个作用域,这 A) 烦人,B) 不容易,因为我不一定有本地作用域.
I'm asking because I'd like to create a helper function that wraps a given function in an $apply
. To do that I'd always need to pass in a scope, which is A) annoying and B) not easy because I don't necessarily have a local scope.
我希望始终在 $rootScope
上调用我的辅助函数 $apply
,但如果这样做有一些风险,则不会.
I'd like to always have my helper function call $apply
on the $rootScope
, but not if there's some risk in doing that.
推荐答案
在任何作用域上运行 $apply
总是会产生 $rootscope.$digest
.它可能会产生影响的唯一情况是当您将表达式作为参数提供给 $apply
时.表达式将在当前作用域(相对于 $rootScope)中计算,但之后 $rootscope.$digest
被总是调用.
Running $apply
on any scope always results in a $rootscope.$digest
. The only case where it might make a difference is when you provide an expression as an argument to $apply
. The expression will be evaluated in the current scope (vs. $rootScope), but afterwards $rootscope.$digest
is always called.
源代码很清楚:rootScope.js
底线:如果您不带参数调用 $apply
,则没有任何区别.
Bottom line:If you call $apply
with no arguments, it makes no difference.
这篇关于在 $rootScope 上运行 $apply 与任何其他范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!