Below is my understanding of how binding happens in angularJS. Would be great if experts can provide feedback/comment..
<div ng-controller="ctrlA">
{{myvar}}
{{anothervar}}
</div>
$scope.watch( function (scope) {
return scope.anothervar;
} , function (oldValue, newValue) {
// code to manupilate HTML with new value!!
});
$scope.watch( function (scope) {
return scope.myVar;
} , function (oldValue, newValue) {
// code to manipulate HTML with new value!!
});
As soon as angularJS encounters {{myVar}} (and {{anothervar}}) a watcher (for each variable) is created internally. This watcher is created for $scope of controller 'ctrlA'.
Whenever functions are called within $timeout, ng-click etc they are embedded within $scope.apply(). After your function is executed (which might change some scope variables), $apply will call digest on the rootScope. This will sync variables throughout the app with the UI!
When $scope.digest is called it iterates through all the watchers for that scope. It then gets the current value of the variable and checks to see if it changed. If it changed it calls the watcher handler (which changes the html to reflect the new value!).
I have a question here. Does angularJS store have some kind of key-map (or some data structure) for every scope, which contains the reference to watcher and the current value for that watcher?? Something like:
watch ref (for myvar) -> current value (of myvar)
watch ref (for anothervar) -> current value (of anothervar)