简体   繁体   English

了解AngularJS官方网站中的双向数据绑定教程

[英]Understanding two-way data binding tutorial in AngularJS official site

I am looking at the official tutorial on AngularJS website that explains two-way data binding. 我正在查看AngularJS网站上的官方教程,该教程解释了双向数据绑定。

https://docs.angularjs.org/tutorial/step_04 https://docs.angularjs.org/tutorial/step_04

The tutorial mentions this: 本教程提到了这一点:

Angular creates a two way data-binding between the select element and the orderProp model. Angular在select元素和orderProp模型之间创建双向数据绑定。 orderProp is then used as the input for the orderBy filter. 然后,将orderProp用作orderBy过滤器的输入。

However, when looking at the live demo I only see one-way binding. 但是,在观看实时演示时,我只能看到单向绑定。

Can anybody explain how that demo is supposed to illustrate two-way data binding? 谁能解释该演示如何说明双向数据绑定?

The tutorial has this explanation (emphasis mine): 本教程有以下说明(重点是我的):

This is a good time to talk about two-way data-binding. 这是讨论双向数据绑定的好时机。 Notice that when the app is loaded in the browser, "Newest" is selected in the drop down menu. 请注意,将应用程序加载到浏览器中后,在下拉菜单中选择了“最新”。 This is because we set orderProp to 'age' in the controller. 这是因为我们在控制器中将orderProp设置为“ age”。 So the binding works in the direction from our model to the UI . 因此,绑定在从模型到UI的方向上起作用 Now if you select "Alphabetically" in the drop down menu, the model will be updated as well and the phones will be reordered. 现在,如果您在下拉菜单中选择“按字母顺序排列”,则型号也会被更新,并且手机将重新排序。 That is the data-binding doing its job in the opposite direction — from the UI to the model. 那就是数据绑定在相反的方向上工作-从UI到模型。

So this is the demonstration of two-way binding. 这就是双向绑定的演示。 Although not very obvious. 虽然不是很明显。

Well, what you see is the binding from the view to the model (you write something in the input box and the view changes). 好了,您看到的是从视图到模型的绑定(您在输入框中写了一些东西,视图随之改变)。

The other way round binding (from the model to the view) is the 'standard' javascript binding: you set a value in a scope variable (linked by Angular to a DOM element), and the view reflects it... 圆形绑定(从模型到视图)的另一种方式是“标准” javascript绑定:您在范围变量(通过Angular链接到DOM元素)中设置一个值,然后视图将其反映出来...

I agree with @Sergio Tulentsev it's not so obvious... :-) 我同意@Sergio Tulentsev并不是很明显... :-)

//ng-model="query" is two way data binding of input to model property query
// any change in model will reflect inside input textbox and vice versa 
Search: <input ng-model="query">

//ng-model="orderProp" will assign selected option to model property orderProp
Sort by:
<select ng-model="orderProp">
  <option value="name">Alphabetical</option>
  <option value="age">Newest</option>
</select>


<ul class="phones">
  //filter:query will filter phones having its property matching words to query and result will be ordered by orderProp that is by name or age 
  <li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
    <span>{{phone.name}}</span>
    <p>{{phone.snippet}}</p>
  </li>
</ul>

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

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