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

时间:2015-09-02 09:57:21

标签: javascript angularjs

我正在查看AngularJS网站上的官方教程,该教程解释了双向数据绑定。

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

教程提到了这一点:

  

Angular在select元素和。之间创建双向数据绑定    orderProp 模型。 orderProp 然后用作输入   orderBy过滤器。

然而,在查看live demo时,我只看到单向绑定。

有人可以解释一下这个演示应该如何说明双向数据绑定吗?

3 个答案:

答案 0 :(得分:1)

本教程有这样的解释(强调我的):

  

这是谈论双向数据绑定的好时机。请注意,当应用程序加载到浏览器中时,在下拉菜单中选择“最新”。这是因为我们在控制器中将orderProp设置为'age'。因此,绑定在从模型到UI的方向上工作。现在,如果您在下拉菜单中选择“按字母顺序”,模型也会更新,电话将被重新排序。这就是数据绑定在相反的方向上发挥作用 - 从UI到模型。

所以这是双向绑定的演示。虽然不是很明显。

答案 1 :(得分:0)

嗯,你看到的是从视图到模型的绑定(你在输入框中写了一些东西,视图也发生了变化)。

圆形装订的另一种方式(从模型到视图)是标准' javascript绑定:在范围变量中设置一个值(由Angular链接到DOM元素),视图反映它......

我同意@Sergio Tulentsev它并不那么明显......: - )

答案 2 :(得分:0)

//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>