$适用VS $文摘指令测试 [英] $apply vs $digest in directive testing
问题描述
如果我有回应有关范围的特定属性的状态指示,我想改变这种属性在我的测试,并确认其正确地响应,这是在做这种变化的最好方法是什么?
If I have a directive that responds to the status of a particular attribute on the scope, and I want to change that attribute in my test and verify that it responds correctly, which is the best way of doing that change?
我见过这两种模式:
scope.$apply(function() {
scope.myAttribute = true;
});
和
scope.myAttribute = true;
scope.$digest();
它们之间有什么区别,而这是更好的,为什么?
What is the difference between them, and which is better and why?
推荐答案
范围。$摘要()
将火在当前范围观察,并在其所有的孩子了。 范围。$适用
将评估通过的功能和运行 $ rootScope。$摘要()
。
scope.$digest()
will fire watchers on the current scope, and on all of its children, too. scope.$apply
will evaluate passed function and run $rootScope.$digest()
.
第一个是速度更快,因为它需要对目前的范围及其子评估观察家。第二个是慢,因为它需要评估 $ rootScope
观察家和它所有的子作用域。
The first one is faster, as it needs to evaluate watchers for current scope and its children. The second one is slower, as it needs to evaluate watchers for$rootScope
and all it's child scopes.
当在观察家之一发生错误并使用范围。$摘要
,它不是通过 $ exceptionHandler的$ C $处理C>服务,所以你需要自己处理异常。
范围。$适用
使用的try-catch
内部阻塞并通过了所有的例外 $ exceptionHandler的
。
When an error occurs in one of the watchers and you use scope.$digest
, it's not handled via $exceptionHandler
service, so you need to handle exception yourself. scope.$apply
uses a try-catch
block internally and passes all exceptions to $exceptionHandler
.
这篇关于$适用VS $文摘指令测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!