E
E
Egor2015-02-17 13:41:06
JavaScript
Egor, 2015-02-17 13:41:06

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 */
}

So now I'm using this design
/* some code */
if(!scope.$phase && !scope.$root.$phase){
scope.$apply();

What potential problems can arise if $apply is called after the code is executed?
Do I understand correctly that the call inside $apply is relevant for asynchronous code, but in the case of sequential execution, there should be no problems?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kazmiruk, 2015-02-17
@ByKraB

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.

V
Valery, 2015-02-17
@Akuma

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.

L
lega, 2015-02-22
@lega

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 question

Ask a Question

731 491 924 answers to any question