When you writer an expression, In the backend angular set up a watcher on the currosponding scope model, which in turns updates the view whenever an update happens on the model.
For example: If you create an expression like {{myValue}} in an angular page, In the backend it create a watch expression looks like follows.
So here the second parameter for the watch expression is a listener function, which will triggered whenever an updation happens the 'myValue' model value. So if a change happens, it will update the 'myValue' currosponding DOM with new value, this logic is writtern inside the listener function
The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:
A value function
A listener function
The $scope.$digest() call helps to firing all watchers .
The $scope.$digest() function iterates through all the watches in the $scope object, and its child $scope objects (if it has any). When $digest() iterates over the watches, it calls the value function for each watch. If the value returned by the value function is different than the value it returned the last time it was called, the listener function for that watch is called.
Angular doesn’t directly call $digest(). Instead, it calls $scope.$apply(), which in turn calls $rootScope.$digest(). As a result of this, a digest cycle starts at the $rootScope, and subsequently visits all the child scopes calling the watchers along the way.
The $scope.$apply() function takes a function as parameter which is executed, and after that $scope.$digest() is called internally. That makes it easier for you to make sure that all watches are checked, and thus all data bindings refreshed.
When Do You Call $apply() Manually?
if you use JavaScript’s setTimeout() function to update a scope model, Angular has no way of knowing what you might change. In this case it’s your responsibility to call $apply() manually, which triggers a $digest cycle. Similarly, if you have a directive that sets up a DOM event listener and changes some models inside the handler function, you need to call $apply() to ensure the changes take effect.
No comments:
Post a Comment