How do the Angularjs Watchers work?

Asked

Viewed 1,552 times

13

In Angularjs, there is the two-way data Binding, which causes the values to be displayed immediately on views even when this value is updated in controller.

In addition there is also the function $scope.$watch who knows exactly when a variable is changed and immediately calls an action when it happens.

My question is:

How does Angularjs do that?

I have this concern because, in a system where I had to use several ng-repeat followed by ng-models, several Watchers were generated and, with this, it is noticeable a great slowness in the rendering of the elements.

I know that in Vue is used a kind of Observer property defined in the object. But I still can’t figure out how it works in Angularjs.

  • Angular internally uses some kind of loop, setInterval, or something from Javascript that lets you watch the variables change? I have this curiosity to understand how this can affect performance and also to try to do something similar.

  • If I use too many Watchers (which are generated by ng-if, ng-model and the like, in addition to $scope.$watch), may impair the performance of my application?

  • 1

    I also got caught up in it, I always imagined an individual Rigger, but recently I came across https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver?tlocale=en-US&redirectslug=DOM%2FMutationObserver, and I believe it is by this way.

1 answer

4

The answer is yes. Every time you use one ng-model , ng-click and etc is made a apply which is access to Digest Cycle encapsulated together with the execution of Expression, causing the entire list of $watches are executed, as in the image este diagrama está na documentação do Angularjs

This way yes if you use many $watchs will harm your performance on the page, why in Angularjs should be careful with Expressions that make function calls, because whenever you make a simple interaction on the page will be called several times.

If you want to go deeper on the subject, I will leave here 2 videos on how to improve the performance of Angularjs.

performance 1 : https://youtu.be/6kIorm_gCO4

performance 2 : https://youtu.be/oUus56DtpO0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.