Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does AngularJS know when variables change? How does AngularJS dirty checking work?

I was reading some article to understand a little bit more how AngularJS works.

One of the terms that I didn't understand is Dirty Checking.

What is it exactly? It seems like the Observer pattern but apparently it's better.

Can you help me understand this please?

EDIT : it can be also useful for people who wants to learn more about that to watch this video from swiip at NgEurope some years ago.

like image 356
mfrachet Avatar asked Jul 11 '14 13:07

mfrachet


People also ask

Does Angular use dirty checking?

How does Angular magically know how to update the content? It uses a technique called dirty checking. Angular tracks the previous values for these various expressions. If it notices a change, the corresponding Angular directive is given a chance to reflect those changes in the DOM.

What is dirty checking in JS?

Dirty checking is called dirty for a reason. It runs periodical checks instead of listening on property changes directly.

How does Digest cycle works in AngularJS?

Digest cycle is what Angular JS triggers when a value in the model or view is changed. The cycle sets off the watchers which then match the value of model and view to the newest value. Digest cycle automatically runs when the code encounters a directive.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.


Video Answer


1 Answers

From this link:

Angular defines a concept of a so called digest cycle. This cycle can be considered as a loop, during which Angular checks if there are any changes to all the variables watched by all the $scopes. So if you have $scope.myVar defined in your controller and this variable was marked for being watched, then you are explicitly telling Angular to monitor the changes on myVar in each iteration of the loop.

This "digest" is also called "dirty checking", because, in a way, it scans the scope for changes. I cannot say if it's for better or for worse than observable pattern. It depends on your needs.

Some links:

  • Angular documentation
  • A blog post about Angular scopes
like image 117
lante Avatar answered Oct 14 '22 15:10

lante