After looking at the source code of Angular, it looks like this: $ timeout makes a call to $ RootScope. $ Apply ().
- Why doesn't $ timeout () also throw an error if the digest loop is already running?
$timeout uses the undocumented Angular $browser . In particular, it uses $browser.defer() , which interrupts the execution of your function asynchronously through window.setTimeout(fn, delay) , which will always work outside the Angular life cycle. Only once window.setTimeout launched your function, there will be a $timeout call to $rootScope.$apply() .
- It is best to use $ scope. $ apply (), if you know for sure that the digest will not be executed, and $ timeout (), when is it necessary for security anyway?
I would say so. Another use case is that sometimes you need to access the $ scope variable, which, as you know, will be initialized after the digest. A simple example could be if you want the state of the form to get dirty inside your controller constructor (for some reason). Without $ timeout, the FormController not initialized and published to $ scope, so wrapping $scope.yourform.setDirty() inside $ timeout ensures that the FormController been initialized. Of course, you can do all this with a directive without $ timeout, just using a different use case.
- Is $ timeout () really acceptable "safe", or are there gotchas?
It should always be safe, but your approach to the method should always target $ apply (), in my opinion. The current Angular application I'm working on is quite large, and we only had to rely on $ timeout, not $ apply ().
Beyers Apr 15 '14 at 3:05 2014-04-15 03:05
source share