Site icon ParallelCodes

AngularJS Data Binding

AngularJS Data Binding

AngularJS Data binding ensures two-way binding and provides synchronization between the view and the model.

Using One-Way Data Binding:

One-way binding only updates HTML view data as per the data in the Model object. Any changes on the Controller declaration of a model variable will get updated on the view object.

This fails to sync data between View,model and when value changes on the view. This can be used when you don’t need to update a Model object from the view.

Example:

<html>
<head>
<title>AngularJS - Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>

</head>
<body ng-app="myApp">

<div ng-controller='myController'>
<p>{{currentDate}}</p>
</div>

<script>
var app = angular.module("myApp",[]).controller("myController", function ($scope){
$scope.currentDate = new Date();
});

</script>

</body>
</html>

VIEW DEMO

This will simply print the date and time. The Expression {{currentDate}} provides no-way to update the model object.


Two-way data binding:

Two-way binding in AngularJS ensures synchronization between the Model class and the view. This ensures that there is always common data between the View and its model class. We can use ng-Model directive for achieving this functionality.

Example:

<html>
<head>
<title>AngularJS - Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>

</head>
<body ng-app="myApp">

<div ng-controller='myController'>
<p>Enter your name:<input type="text" ng-model="name"/></p>
<p ng-bind="name"></p>
</div>

<script>
var app = angular.module("myApp",[]).controller("myController", function ($scope){
$scope.name = "Big show ";
});

</script>

</body>
</html>

VIEW DEMO

OUTPUT:


References: AngularJS API DOC


Exit mobile version