Tuesday, 14 March 2017

How to use 2-way data binding using ng-model ?


2-WAY DATA BINDING

KEEPS MODEL AND VIEW IN SYNC
  • Change in Model > Updates View automatically
  • Change in View > Updates Model automatically

EXAMPLE 1. Model > View
var app = angular
              .module('module1', [])
              .controller("controller1", function ($scope) {
                    $scope.message = "Hello Angular";
              });




 

<div ng-controller="controller1">
      {{ message }}
</div>
 



EXAMPLE 2. Two-way Data Binding : View > Model  (Using ng-model)

<div ng-controller="controller1">
      <input type="text" ng-model="message" />
      <br /> <br />
      {{ message }}
</div>


The value provided / changed in text box will reflect the Model, which will also change value displayed by {{ xyz }} binding expressions.


The power of ng-model
  • ng-model can be used with <select> and <textarea> also
  • ng-model also work with complex objects.
    <input type="text" ng-model="employee.name" />

What will happen if the given variable in ng-model is not defined ?
<input type="text" ng-model="username" />
Note : If the 'username' is not defined, still it will create a new model.



No comments:

Post a Comment

Note: only a member of this blog may post a comment.