How to Create Data Binding Using Angularjs?

There is automatic synchronization of data between the Data Binding Model and View Components in AngularJS. Data Binding is used for software development and technologies. Data Binding is a very useful feature, it acts as a bridge between the Visual Business and Argument of the Application.

Most of the templates bind data in only one direction. It merges the Template and Model Components together in a View, after the merger, it changes in the relevant section of the Model or View and they are not automatically visible in the View.

It is not reflected in the model. This means that the developer has to write code that continuously syncs View with View and Model with View.

Types of Data Binding

There are two types of Data Binding

  1. One-Way Data Binding
  2. Two-way Data Binding

One-Way Data Binding

In One-Way Data Binding, the View is not updated automatically and the Data Model changes. We have to write custom code to update every time. This is not a synchronization procedure and it will process the data in the same way.

Two-way Data Binding

In Two-Way Data Binding, the View is updated automatically when the Data Model is changed. Using ng-model Directive we can achieve Two-Way Data Binding. If we use Ng-model Directive in HTML control then this Input gets updated automatically and gets converted into Data Input control.

For Example

<!DOCTYPE html> 
<html>
<head>
<script src ="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
</head>
<body>
<div ng-app="" ng-init="firstName='Jyoti'">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
</body>
</html>

Output

Name:

{{firstname}}

In the above example {{firstName}} Expression is an AngularJS Data Binding Expression. Data Binding in AngularJS is the binding of AngularJS Expressions with AngularJS Data.

{{ firstName }} is bound with ng-model=”firstName”

Let’s look at another example where two text fields are bound together with two ng-model instructions.

For Example

<!DOCTYPE html> 
<html>
<head>
<script src ="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
</head>
<body>
<div data-ng-app="" data-ng-init="quantity=1;price=20">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity">
Price: <input type="number" ng-model="price">
<p><b>Total in rupees:</b> {{quantity * price}}</p>
</div>
</body>
</html>

Output

Cost Calculator

Quantity: Price:

Total in rupees: {{quantity * price}}