2

I am curious to know how angular js watches mutations which happens to a property added to $scope. From HTML point of view, I am able to get it, that we have some events which are fired whenever there's a change. But when it's regarding an object I am not able to understand how it actually works. I can see we have a function called Object.observe. But that is also deprecated as written here. And I am pretty much sure that angular does not use Object.observe. The doc of angular says that one can watch mutations using $watch and $watchCollection. But I am not able to get how these are notified. Can anyone help on this?

Hitesh Kumar
  • 3,508
  • 7
  • 40
  • 71
  • Maybe check this: http://stackoverflow.com/questions/19304559/how-to-watch-the-dom-for-changes-angularjs and this: http://www.bennadel.com/blog/2852-understanding-how-to-use-scope-watch-with-controller-as-in-angularjs.htm - The second one goes a bit in-depth about `$watch`. – Angelos Chalaris Jun 07 '16 at 08:31
  • @chalarangelo: I don't think that's what they're asking - they want to know how Angular's change tracking works, not how to watch the DOM. – Joe Clay Jun 07 '16 at 08:32
  • https://www.binpress.com/tutorial/angular-js-looking-under-the-hood/153 – lexeme Jun 07 '16 at 08:36
  • I want to know that let's say I have $scope.name='Hitesh Kumar'. Now If I change it to $scope.name='HK' then how does angular js is notified about it. – Hitesh Kumar Jun 07 '16 at 08:36

1 Answers1

4

Angular will actually take a copy of the object being watched and compare against it every digest loop. So there are no notification when things change. It looks for changes every loop. And that's why watching can be expensive. The more watches you have, the more comparisons needs to be made, and in the case where changes are found, you might end up with a new run to make sure that the change that was detected doesn't affect one of the watched objects that you already checked.

I would suggest the book 'Build you own AngularJS' by Tero Parviainen. Even though it's not a 100% accurate source recreation, the concepts are the same, and you'll get good insight in how angular works.

Another source for understanding this part of angular is the chapter 'The Digest Loop and $apply' of the 'ng-book'. The concept is described there in a more 'accessible' form than in Teros book.

Vegar
  • 12,828
  • 16
  • 85
  • 151