AngularJS Data Binding

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Data binding is a very useful and powerful feature used in software development technologies. It acts as a bridge between the view and business logic of the application.

AngularJS follows Two-Way data binding model.

One-Way Data Binding

The one-way data binding is an approach where a value is taken from the data model and inserted into an HTML element. There is no way to update model from view. It is used in classical template systems. These systems bind data in only one direction.

One Way Data Binding

Two-Way Data Binding

Data-binding in Angular apps is the automatic synchronization of data between the model and view components.

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. If the model is changed, the view reflects the change and vice versa.

Two Way Data Binding

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src=""></script>  
  4. <body>  
  5. <div ng-app="" ng-init="firstName='Ajeet'">  
  6. <p>Input something in the input box:</p>  
  7. <p>Name: <input type="text" ng-model="firstName"></p>  
  8. <p>You wrote: {{ firstName }}</p>  
  9. </div>  
  10. </body>  
  11. </html>  

In the above example, the {{ firstName }} expression is an AngularJS data binding expression. Data binding in AngularJS binds AngularJS expressions with AngularJS data.

{{ firstName }} is bound with ng-model="firstName".

Let's take another example where two text fields are bound together with two ng-model directives:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src=""></script>  
  4. <body>  
  5. <div data-ng-app="" data-ng-init="quantity=1;price=20">  
  6. <h2>Cost Calculator</h2>  
  7. Quantity: <input type="number" ng-model="quantity">  
  8. Price: <input type="number" ng-model="price">  
  9. <p><b>Total in rupees:</b> {{quantity * price}}</p>  
  10. </div>  
  11. </body>  
  12. </html>