angularjs中单向绑定和双向绑定之间的区别 [英] Difference between one way binding and two way binding in angularjs
问题描述
您能否举例说明One-way Data Binding
和Two-way Data Binding
之间的区别以及我们使用的是哪种情况?
Could you explain the difference between One-way Data Binding
and Two-way Data Binding
with an example and which situation we used?
推荐答案
单向数据绑定
ng-bind
具有单向数据绑定(Model($scope) --> View)
例如.
ng-bind="myText"
或{{ myText }}
ng-bind
has one-way data binding (Model($scope) --> View)
Eg.
ng-bind="myText"
OR {{ myText }}
显示插入到HTML中的范围值$scope.myText
,其中myText
是范围变量名称.(例如,Model-> View)
which displays the scope value $scope.myText
inserted into HTML where myText
is a scope variable name.(E.g., Model -> View)
双向数据绑定
ng-model
主要用于放置在表单元素内部,并具有双向数据绑定
ng-model
is intended to be put mostly inside form elements and has two-way data binding
(Model($scope) --> View and View --> Model($scope))
例如. <input name="firstname" ng-model="firstname"/>
当与ng-model
与$scope.firstname
交互的表单元素firstname
交互并在Digest
周期内自动更新相应的视图.(例如,模型->视图和视图->模型)
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 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>
一旦firstname
被定义并包含一个值,AngularJS将对其进行unbind
,并且任何模型更新都不会影响视图.
Once firstname
becomes defined and contains a value, AngularJS will unbind
it and any Model updates won’t affect the View.
例如.使用 ng-if
<div ng-if="::user.firstname"></div>
使用 ng-class
<div ng-class="::{ 'active': user.firstname }"></div>
使用 ng-repeat
<ul>
<li ng-repeat="user in ::users"></li>
</ul>
这篇关于angularjs中单向绑定和双向绑定之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!