How do AngularJS watchers work?

13

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

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

My question is:

How does AngularJS do this?

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, a great slowness in rendering the elements .

I know that in Vue a kind of observer is used in the property defined in the object. But I still can not figure out how this works in AngularJS.

  • Does Angular internally use some kind of loop , setInterval , or something from JavaScript that allows you to watch change in variable values? I have this curiosity to understand how this can affect the performance and also to try to do something similar.

  • If I use many watchers (which are generated by ng-if , ng-model , and the like, plus the $scope.$watch itself), can I damage the performance of my application? / p>

asked by anonymous 31.10.2017 / 11:42

1 answer

4

The answer is yes. Every time you use a ng-model , ng-click , and so on% is done apply which is access to the digest cycle encapsulated along with the execution of the expression, causing the entire list of $watches are executed, as in the

Inthisway,ifyouusetoomany$watchsitwillhurtyourperformanceonthepage,soinAngularjsbecarefulwithexpressionsthatmakecallstofunctions,becausewheneveryoudoasimpleinteractiononthepageyouwillbecalledseveraltimes.

Ifyouwanttogodeeperintothesubject,I'llleaveheretwovideosonhowtoimprovetheperformanceofAngularjs.

performance1: link

performance 2: link

    
07.11.2017 / 00:48