Answer the question
In order to leave comments, you need to log in
Angular. Is it necessary to put code inside $apply?
Greetings.
There are some places in the code where you need to use $apply. To avoid getting unnecessary errors, I check if $apply or $digest is currently running if(!scope.$phase && !scope.$root.$phase)
. Because of this condition, it becomes not very convenient to execute the code inside $apply, because you have to duplicate the code.
if(!scope.$phase && !scope.$root.$phase){
scope.$apply(function(){
/* some code */
});
}else{
/* some code */
}
/* some code */
if(!scope.$phase && !scope.$root.$phase){
scope.$apply();
Answer the question
In order to leave comments, you need to log in
It's bad to do this https://github.com/angular/angular.js/wiki/Anti-Pa...
You can make it easier
$timeout(function() {
code
});
The effect will be the same. Well, all this is relevant for code that changes the state from the outside.
There doesn't seem to be any difference. I myself have been using the second method for quite a long time and have never had any problems because of this.
If your code doesn't cause infinite recursion/loops then there won't be any problems.
Unlike $timeout, this will be faster because +1 redrawing will occur with $timeout, $digest is restarted, and all this is delayed in time. Although in most cases it's all the little things.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question