Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between one way binding and two way binding in angularjs

Tags:

angularjs

Could you explain the difference between One-way Data Binding and Two-way Data Binding with an example and which situation we used?

like image 449
Arul Avatar asked Jul 28 '16 02:07

Arul


People also ask

What is two way binding in AngularJS?

Two-way Binding Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.

What is one way binding in AngularJS?

The one-way data binding is an approach where a value is taken from the data model and inserted into an HTML element. There is no way to update model from view. It is used in classical template systems. These systems bind data in only one direction.

What is 2way binding?

Two-way binding gives components in your application a way to share data. Use two-way binding to listen for events and update values simultaneously between parent and child components.


1 Answers

One-Way Data Binding

ng-bind has one-way data binding (Model($scope) --> View) Eg. ng-bind="myText" OR {{ myText }}

which displays the scope value $scope.myText inserted into HTML where myText is a scope variable name.(E.g., Model -> View)

Two-Way Data Binding

ng-model is intended to be put mostly inside form elements and has two-way data binding

(Model($scope) --> View and View --> Model($scope))

Eg. <input name="firstname" ng-model="firstname"/>

When you interact with form element firstname to which ng-model interact with $scope.firstname and update the corresponding view automatically by Digest cycle.(E.g., Model -> View and View -> Model)

One-Time Data Binding

The new syntax adds :: in front of any values(One-way or Two-way), which declares we want one time binding:

<p>   {{ ::firstname }} </p> 

Once firstname becomes defined and contains a value, AngularJS will unbind it and any Model updates won’t affect the View.

Eg. When using ng-if

<div ng-if="::user.firstname"></div> 

When using ng-class

<div ng-class="::{ 'active': user.firstname }"></div> 

When usine ng-repeat

<ul>   <li ng-repeat="user in ::users"></li> </ul> 
like image 52
Arul Avatar answered Oct 04 '22 10:10

Arul