Could you explain the difference between One-way Data Binding
and Two-way Data Binding
with an example and which situation we used?
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With