Data Binding In AngularJS

For learning the basics of AngularJS, you can follow my previous blog: Getting Started With AngularJS
 
Firstly, we clear out our basic concepts, like what is data binding and what are the types of data binding etc.
 
What is data binding?

Data binding is a process of establishing the connection between View and Model to communicate or updating the data from View to model and from Model to View.
Type of binding 

Data binding is of 3 types, as listed below.
  1. One time binding.
  2. One way binding.
  3. Two way binding.
One time binding
  • In One time binding, the data is bound only once through the execution of application
  • Value can't be changed after the data binding from Model to View.
Example
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>  
  7. </head>  
  8.   
  9. <body>  
  10.     <div ng-app>  
  11.         <h1>one time binding in AngularJs</h1> enter you name:<input type="text" ng-model="name">  
  12.         <p>hello mr.{{::name}}</p>  
  13.     </div>  
  14. </body>  
  15.   
  16. </html>  
Output

 
One way Binding

In One way binding, the data is bound in one direction, which means Model to View. If the Model is updated, then the View is also updated but if only the View is updated, no Model is updated.
Example
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>  
  6. </head>  
  7.   
  8. <body ng-app ng-init="firstName = 'Ajay'; lastName = 'Malik';">  
  9.     <strong>First name:</strong> {{firstName}}<br />  
  10.     <strong>Last name:</strong> <span ng-bind="lastName"></span>  
  11. </body>  
  12.   
  13. </html>  
Output

  
Two way binding

In Two way binding, if the Model is updated, then View is also updated and vice versa
Example 
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>  
  6. </head>  
  7.   
  8. <body>  
  9.     <div ng-app ng-init="name='Ajay Malik'">  
  10.         <h1>Two Way binding</h1> Enter your name<input type="text" ng-model="name">  
  11.         <p ng-bind="name">Hello Mr.</p>  
  12.   
  13.     </div>  
  14. </body>  
  15.   
  16. </html>  
output
 
Ebook Download
View all
Learn
View all