简体   繁体   English

AngularJS:ng-options刷新时ng-model不更新

[英]AngularJS: ng-model does not update when ng-options refreshes

I'm new to AngularJS, so I apologize if this question is naive. 我是AngularJS的新手,所以我很抱歉这个问题很幼稚。

We have cascading selects that populate as you select values. 当您选择值时,我们会填充级联选择。 When the value of Select A changes, the values in Select B also change since they filter based on the value in Select A. 当选择A的值更改时,选择B中的值也会更改,因为它们基于选择A中的值进行过滤。

So here is the scenario: 所以这是场景:

  1. Choose option from Select A 从选择A中选择选项
  2. Choose option from Select B 从选择B中选择选项
  3. Change selection for Select A 更改选择A的选择
  4. Observe that options in Select B update accordingly. 请注意,选择B中的选项会相应更新。
  5. Observe that bound model for Select B does not update accordingly. 请注意,Select B的绑定模型不会相应更新。

This seems so basic that we are really scratching our heads. 这似乎很基础,我们真的很难抓。 What is the point of two-way data binding if this scenario isn't covered? 如果不解决此问题,双向数据绑定有什么意义?

Here is my view: 这是我的看法:

    <body ng-controller="MainCtrl">
   Make:
    <select ng-model="makeng" ng-options="option.value as option.display for option in makes">
        <option ng-disabled="true"  ng-selected="true" value="">Select a make</option>
    </select>
  <br /> 
  {{makeng}}

  <br /> <br /> 

  Model:
    <select ng-model="modelng" ng-options="option.display for option in models | filter:{make:makeng}">
        <option ng-disabled="true"  ng-selected="true" value="">Select a model</option>
    </select>
    {{modelng}}
  </body>

Here's a Plunkr, demonstrating: http://plnkr.co/edit/9XrKgW?p=preview 这是一个Plunkr,演示: http ://plnkr.co/edit/9XrKgW?p=preview

PS The above example is purely fictional and forked from another plunkr. PS上面的例子纯粹是虚构的,是从另一个笨蛋派生出来的。 Just the easiest way to demonstrate what we are seeing. 展示我们所见所见的最简单方法。

This is how it is supposed to work. 这是应该如何工作的。 The select control changes the model in response to a user's selection, but if you change the set of allowed values from underneath it (ie by filtering out) it keeps the model intact. select控件会根据用户的选择更改模型,但是如果您从其下方更改允许值集(即通过过滤),则它将保持模型完整。

The way to make this work is by invalidating the model in response to a change in Select A : 进行此工作的方法是通过响应Select A的更改使模型无效:

Make:
<select ng-model="makeng" 
      ng-options="option.value as option.display for option in makes"
      ng-change="modelng = undefined">
   <option value="">Select a make</option>
</select>
<br /> 

Model:
<select ng-model="modelng" 
        ng-options="option.display for option in models | filter:{make:makeng}">
   <option value="">Select a model</option>
</select>

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

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