Angular Two Way Binding ($digest,$watch and $apply())


HI guys today we will see the concept of Angular Two Way Binding and Angular $watch. First of all let’s understand what Angular Two Way Binding is.

What is Two Way Binding ?-
Angular provide a very unique Data-Binding system. Most of Template System binds data only once and if we want to update the template we have to refresh our page. But in Angular template System it is consistently updated when we change the value, any changes to the view are immediately reflected in the model, and any changes in the model are propagated to the view
According to angular official documentation “Data-binding in AngularJS apps is the automatic synchronization of data between the model and view components. The way that AngularJS implements data-binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. When the model changes, the view reflects the change, and vice versa.”

How it is done internally?-

When you create a data binding from somewhere in your view to a variable on the $scope object, AngularJS creates a "watch" internally. A watch means that AngularJS watches changes in the variable on the $scope object. The framework is "watching" the variable. Watches are created using the $scope.$watch() function.

To understand this concept we have to know about Angular $digest() function of Angular. This function iterates through all watches and checks if any of the watched variables have changed. If a watched variable has changed, a corresponding listener function is called. The listener function does whatever work it needs to do, for instance changing an HTML text to reflect the new value of the watched variable. Thus, the $digest() function is what triggers the data binding to update.

Now Have a look on the $scope.$apply() function is used to execute some code, and then call $scope.$digest() after that, so all watches are checked and the corresponding watch listener functions are called. The $apply() function is useful when integrating AngularJS with other code.
Now have a look on the demo. I have created an AngularJs app in which I am showing Two Way Binding of AngularJs.
• When app is loaded at first time , the value for $scope.firstName is to view in input field and template
• When we change the value in input field, the template value is reflected immediately.