AngularJS has powerful data-binding feature which
saves developer from writing boilerplate code (i.e. the sections of code
which is included in many places with little or no alteration).
Developers are not responsible for manually updating HTML elements to
reflect model changes. AngularJS provides its powerful data-binding
mechanism to handle the synchronization of data between model and view.
How AngularJS handle data binding
AngularJS handle data-binding mechanism with the help of three powerful functions: $watch(), $digest() and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest() functions for you, but in some cases you may have to call these functions yourself to update new values.Two-way data binding
It is used to synchronize the data between model and view. It means, any change in model will update the view and vice versa. ng-model directive is used for two-way data binding.Issue with two-way data binding
In order to make data-binding possible, Angular uses $watch APIs to observe model changes on the scope. Angular registered watchers for each variable on scope to observe the change in its value. If the value, of variable on scope is changed then the view gets updated automatically.This automatic change happens because of $digest cycle is triggered. Hence, Angular processes all registered watchers on the current scope and its children and checks for model changes and calls dedicated watch listeners until the model is stabilized and no more listeners are fired. Once the $digest loop finishes the execution, the browser re-renders the DOM and reflects the changes.
By default, every variable on a scope is observed by the angular. In this way, unnecessary variable are also observed by the angular that is time consuming and as a result page is becoming slow. Hence to avoid unnecessary observing of variables on scope object, angular introduced one-way data binding.
One-way data binding
This binding is introduced inAngular 1.3
. An expression that starts with double colon (::)
, is considered a one-time expression i.e. one-way binding.Data Binding Example
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>AngularJS Data Binding : Web Geek School</title>
</head>
<body ng-app="app">
<div ng-controller="Ctrl">
<h2>AngularJS Data Binding</h2>
<p>Name (two-way binding): <input type="text" ng-model="name" /></p>
<i>Change the Textbox value to see changes</i>
<p>Your name (one-way binding): {{::name}}</p>
<p>Your name (normal binding): {{name}}</p>
</div>
<script>
var app = angular.module('app', []);
app.controller("Ctrl", function ($scope) {
$scope.name = "Shailendra Chauhan"
})
</script>
</body>
</html>
AngularJS Data Binding
Name (two-way binding):Change the Textbox value to see changes
Your name (one-way binding): Shailendra Chauhan
Your name (normal binding): 44444
No comments:
Post a Comment