What does $ scope do. $ Apply ()?

I used $scope.$apply() to update the bindings for my models when I receive data through websockets in my Angular applications and this works. But what is he really doing and why should he be called in order to achieve the update?

+4
source share
3 answers

From Angular docs :

$ apply () is used to execute an expression in angular from outside the angular frame. (For example, from browser events DOM, setTimeout, XHR or third-party libraries). Because we call in the angular structure we need to execute the correct life cycle exception handling, clock execution.

The documentation also contains pseudo-code:

 function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } 

In short, $apply evaluates the expression and starts the digest loop, making angular execute all registered observers and update any kind of bindings.

Finally, you said that you use $apply to update bindings for your models, but this is only required when the update is from outside Angular. In most cases, you do not need to call it manually.

+1
source

If you call $apply , the provided code will be executed in angular-context , which you can use, which angular provides.

From link :

Angular modifies the normal JavaScript flow by providing its own event loop. This breaks down JavaScript into a classic and angular execution context. Only operations that apply in the context of angular execution will be useful to angular data binding, exception handling, property viewing, etc.

enter image description here

You can also use $ apply () to enter the angular execution context from JavaScript. Keep in mind that in most places (controllers, services) $ apply is already called by the directive that handles the event. An explicit call to $ apply is only necessary when implementing custom event callbacks or when working with third-party library callbacks.

+3
source

Simply put:

  • (optional) processes the expression that you pass to it as an argument.
  • Calls $ digest () on $ rootScope.

I also wrote a blog post about what $ apply, $ digest and $ watch do and how they work together

I hope this helps.

+1
source

Source: https://habr.com/ru/post/1501398/


All Articles