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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With