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

Angular. Is it necessary to put code inside $apply?

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){
/* some code  */
/* some code */

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

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)
kazmiruk, 2015-02-17

It's bad to do this https://github.com/angular/angular.js/wiki/Anti-Pa...
You can make it easier
$timeout(function() {
The effect will be the same. Well, all this is relevant for code that changes the state from the outside.

Valery, 2015-02-17

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.

lega, 2015-02-22

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