【问题标题】:Angular directive ng-selected doesn't update modelAngular 指令 ng-selected 不更新模型
【发布时间】:2013-01-16 03:31:40
【问题描述】:

在选项上使用角度指令 ng-selected 时,绑定模型在您手动更改选择之前不会更新。这是设计好的吗?

http://jsfiddle.net/PqHsL/1/

<div ng-app ng-init="colors=['red', 'yellow', 'blue']">
  <select ng-model=selectedElement>
    <option ng-repeat="color in colors" value="{{color}}" ng-selected="$last">{{color}}</option>
  </select>

  selectedElement: {{ selectedElement }}
</div>

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    我不知道它是否按设计工作。

    我觉得 ng-selected 和 ng-model 不能很好地配合使用。 (请注意,ng-selected API page 在示例选择列表中没有使用 ng-model。)

    这里有两种解决方法:

    1. 除了设置 ng-selected 之外,还设置绑定模型。 ng-init 也可以用于此:
      ng-init="colors=['red', 'yellow', 'blue']; selectedElement=colors[colors.length-1]"

    2. 设置绑定模型,不使用ng-selected,使用ng-options:
      ...ng-init as above...
      &lt;select ng-model=selectedElement ng-options="color for color in colors"&gt;{{color}}&lt;/select&gt;

    Fiddle.

    解决方案 1 有一个奇怪的“空白”/空选项,当您选择某些内容时它会消失。解决方案 2 没有空选项,并且不那么冗长。 (所以是的,我喜欢解决方案 2。)

    如果我们可以将模型设置为预选选项,我不确定 ng-selected 的用例是什么。稍后我们也可以通过编程方式更改选择 - 请参阅 Fiddle 中的 ng-click。

    【讨论】:

    • 我使用了#2,但是,是的,必须先明确设置模型。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2017-04-02
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多