问题描述
以下是用于测试指令的非常常见的通用场景:
Below is a very common generic scenario used for testing directive:
var element,scope;
beforeEach(inject(function ($rootScope,$compile) {
scope = $rootScope.$new()
element = angular.element('<div my-directive></div>')
$compile(element)(scope)
scope.$digest(); //why?
}))
我理解 $ compile(element)
返回一个带有范围参数的函数并将其提供给元素的指令。我也明白范围。$ digest()
执行摘要循环并开始脏检查。尽管如此,我的问题是为什么你必须在调用 $ compile
之后调用范围。$ digest
一切都适用于这种情况?
I understand $compile(element)
returns a function that take a scope parameter and provides it to the element's directive. I also understand that scope.$digest()
executes the digest loop and start dirty-checking. With all that said, my question is why you have to call the scope.$digest
after calling $compile
to make everything works in this situation?
推荐答案
这是用于测试指令的通用代码。 $ Compile
使用范围绑定模板并执行 link
函数和 $ digest
/ $ apply
刷新可能已被链接
修改的模型的绑定。
当您在 ng-click
处理程序或控制器函数中调用 $ compile
时,整个执行将在<$内部运行c $ c> $ digest 循环。 Angular以这样的方式构建,即动态添加的项(在执行此循环时)在同一循环中执行。这就是为什么你实际上没有注意到差异,并且没有意识到编译后需要绑定评估。然而,它在单元测试中有所不同,你应该告诉angular手动执行 $ digest
循环。例如,在测试 $ q
承诺时,这通常会导致问题。
This is a generic code for testing a directive. $Compile
binds template with scope and executes link
function and $digest
/$apply
refreshes bindings for models that might have been modified by link
.
When you call $compile
inside ng-click
handler or in controller function, the whole execution is run inside a $digest
loop. Angular is built in such a way that dynamically added items (while executing this loop) are executed in same cycle. That is why you don't actually notice the difference and don't realize the need for binding evaluations after compilation. However it's way different in unit tests, where you should tell angular to execute a $digest
cycle manually. This often results in problems when testing $q
promises, for example.
这篇关于为什么在单元测试中的$ compile(element)(范围)之后调用scope。$ digest()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!