Two-Way Data Binding In AngularJS

Keep the model and the view in sync at all times; what is changed in the model updates the view and what is changed in the view updates model.

model

Let’s start to understand two way data binding.

  1. var myApp = angular  
  2. .module("myModule", [])  
  3. .controller("myController"function ($scope) {  
  4.     $scope.message = "Two way data Binding";  
  5.   
  6. });  

Within our controller function we have $scope object that we attach message variable to and within this variable we have stored message “Two way data binding”. To display this model data within our view we use data binding expression {{message}}

 

When we run this application we should see the model data “Two way data Binding”.

 
The binding expression updates the view when model is changed but what if you want it the other way round? When view changes the model updates automatically; that exactly is  the purpose of ng-model directive. ng-model directive updates the model when the view changes. Let’s include a text box in view.
  1. <input type="text" ng-model="message" />  
 

When we run the application then look at the value in the  text box -- it is the same as in our module because of ng-model="message". When we change in text box the automatic message changes so that we have  two way data binding.

Up Next
    Ebook Download
    View all
    Learn
    View all