Why call scope.$digest() after $compile(element)(scope) in unit testing

孤街醉人 提交于 2019-12-07 05:42:21

问题


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?
}))

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?


回答1:


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.



来源:https://stackoverflow.com/questions/31373772/why-call-scope-digest-after-compileelementscope-in-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!