简体   繁体   English

angularjs中单向绑定和双向绑定之间的区别

[英]Difference between one way binding and two way binding in angularjs

你能解释的区别One-way Data BindingTwo-way Data Binding与我们使用的例子,它的情况?

One-Way Data Binding 单向数据绑定

ng-bind has one-way data binding (Model($scope) --> View) Eg. ng-bind具有单向数据绑定(Model($scope) --> View)例如。 ng-bind="myText" OR {{ myText }} ng-bind="myText"{{ myText }}

which displays the scope value $scope.myText inserted into HTML where myText is a scope variable name.(Eg, Model -> View) 它显示了插入HTML的范围值$scope.myText ,其中myText是范围变量名。(例如,模型 - >视图)

Two-Way Data Binding 双向数据绑定

ng-model is intended to be put mostly inside form elements and has two-way data binding ng-model主要用于表单元素,并具有双向数据绑定

(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.(Eg, Model -> View and View -> Model) 当您与表单元素firstname进行交互时, ng-model$scope.firstname进行交互,并通过Digest循环自动更新相应的视图。(例如,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 : 新语法在任何值( 单向或双向 )前添加:: ,声明我们需要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. 一旦firstname被定义并包含一个值,AngularJS将unbind它,任何Model更新都不会影响View。

Eg. 例如。 When using ng-if 使用ng-if时

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

When using ng-class 使用ng-class时

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

When usine ng-repeat 使用重复时

<ul>
  <li ng-repeat="user in ::users"></li>
</ul>

One way binding is bind the data from model to view. 单向绑定是将数据从模型绑定到视图。 Also two way binding is bind the data from model to view and view to model. 另外,双向绑定是将数据从模型绑定到视图并查看到模型。

data binding in UI is the binding of UI fields to a data model. UI中的数据绑定是UI字段与数据模型的绑定。 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. 无论在UI上发生什么,都会触发建模消息以更新部分数据。 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. 双向数据绑定 - > UI字段中的任何更改都会更新模型,模型中的任何更改都会更新UI字段。

one way data binding is better approach because of unidirectional flow of data. 由于数据的单向流动,单向数据绑定是更好的方法。 Also only model has the access to change the application state. 此外,只有model可以访问更改应用程序状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM