指令测试中的 $apply 与 $digest [英] $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?
推荐答案
scope.$digest()
将在当前作用域及其所有子作用域上触发观察者.scope.$apply
将评估传递的函数并运行 $rootScope.$digest()
.
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.
当其中一个观察者发生错误并且您使用scope.$digest
时,它不会通过$exceptionHandler
服务进行处理,因此您需要自己处理异常.scope.$apply
在内部使用 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
.
这篇关于指令测试中的 $apply 与 $digest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!