Data-binding in AngularJs

There are two types of data-binding in AngularJs:

1. One-Way Binding/ Basic Data-Binding

2. Two-way Binding

One-Way Binding:

A data binding can be specified in two different ways:

  • with curly braces: {{expression}}
  • with the ng-bind directive: ng-bind=“varName”

Example to show one-way binding:

HTML page(View):

<!DOCTYPE html>
<html>
<head>
<script src=”angular.js”></script>
</head>

<body ng-app ng-init=”firstName = ‘Daniel'; lastName = ‘Smith';”>
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> <span ng-bind=”lastName”></span>
</body>
</html>

We’re saying one way data binding because the model values (here the variables represent the model) are automatically assigned to the HTML placeholder elements specified through the data binding notation, but the HTML elements don’t change the values in the model (one way).

Two-way data binding:

We have a two way data binding when a model variable is bound to a HTML element that can both change and display the value of the variable. In general, we could have more than one HTML element bound to the same variable. We use the ng-model directive to bind a model variable to the HTML element that can not only display its value, but also change it.

<!DOCTYPE html>
<html>
<head>
<script src=”angular.js”></script>
</head>

<body ng-app ng-init=”firstName = ‘Daniel'; lastName = ‘Smith';”>
<strong>First name:</strong> {{firstName}}<br />
<strong>Last name:</strong> <span ng-bind=”lastName”></span><br />
<br />
<label>Set the first name: <input type=”text” ng-model=”firstName”/></label><br />
<label>Set the last name: <input type=”text” ng-model=”lastName”/></label>
</body>
</html>

In the example, we bind the firstName and lastName model variables to a couple of HTML input elements. When the page is loaded, the value of the input elements are initialized to those of the respective model variables and whenever the user types something in an input, the value of the model variable is modified as well (two way).


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>