Two Way Binding in AngularJS

Two-way data binding is when the model changes, the view reflects the change, and vice versa. When we have more than one html element bound to the same model variable.HTML element that can both change and display the value of the variable. Two-way bindings in AngularJS are created with the ng-model directive.

Step 1: Make a AngularJS module and controller.

  1. var app=angular.module("myApp", [])  
  2. app.controller("myCtrl" ,function($scope) {  
  3.   $scope.firstName = "virendra";  
  4.     $scope.lastName="Gour";  
  5. });  
Step 2: Create html page and use directives.
  1. <div ng-app="myApp">  
  2.   <div ng-controller="myCtrl">  
  3.             <input type="text" ng-model="firstName">  
  4.          <input type="text" ng-model="lastName">    
  5.              <br />  
  6.              <span ng-bind="firstName"></span>  
  7.            <span ng-bind="lastName"></span>  
  8.   </div>  
  9. </div>  
Here is calling our controller by ng-controller directive and we have two input text decorates by ng-mode directive. Values of variable firstName and lastName will display in input text and also in span but magic is that when you will change the values of input text changes will also reflect in span.

output

Ebook Download
View all
Learn
View all