Could you explain the difference between One-way Data Binding and Two-way Data Binding with an example and which situation we used?
3 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>
3 Comments
data binding in UI is the binding of UI fields to a data model. There are two approaches of data binding : one way data binding and two way data binding
one way data binding -> model is the single source of truth . whatever happens on UI triggers a message to model to update a part of data. So data flows in single direction and which becomes easy to understand.
two way data binding -> any change in UI field updates the model and any change in model updates the UI field.
one way data binding is better approach because of unidirectional flow of data. Also only model has the access to change the application state.