ng-selected是如何工作的?

25

这里是一个片段。我选择了Q2,正如我所预期的那样。

<select name="quarter" ng-model="Quarter" >
    <option value="1" >Q1</option>
    <option value="2" ng-selected="Quarter=='Q1'">Q2</option>
    <option value="3">Q3</option>
    <option value="4">4</option>
</select>

'Q1'更改为'Q2'并没有使所选内容像我期望的那样。现在加上ng-selected="Quarter=='Q1'"并不会选择Q1,直到我删除ng-selected="Quarter=='Q2'"

这是怎么回事?


这对我来说似乎是有效的,或者这不是你想做的吗?http://jsfiddle.net/xpjaD/ - Ronnie
@Ronnie:这就是我想做的。WTH。我删除了除了Q1分配以外的所有控制器代码,但是......我猜在HTML中有些东西出了问题。 - BruteCode
@Ronnie:相关问题:https://dev59.com/SnDYa4cB1Zd3GeqPAG_L - BruteCode
最简单的方法是使用<b>ng-init</b><br> 请参照此示例 - T-Bee
4个回答

21
如果您在选项元素上放置ng-selected,当ng-selected的值为true时,您的选项将被选中。在您的情况下,当Quarter等于Q1时,选项Q2被选中。
如果您想选择传递给Quarter的值,则必须在select元素上放置ng-selected:
<select name="quarter" ng-model="Quarter" ng-selected="Quarter"
        ng-options="Quarter for Quarter in Quarters" >
    {{Quarter}}
</select>

请查看选择指令文档


有趣但也是令人困惑的。我在api网站docs.angularjs.org/api/上没有看到ng-options。而且它似乎不能与ng-repeater一起使用https://dev59.com/SnDYa4cB1Zd3GeqPAG_L。 - BruteCode
ng-options是select指令的一个属性: doc.angularjs - Bastien Caudan
由于嵌入式 iframe 是唯一的内容,您的小提琴被标记为不安全...!!! 看起来有些可疑! - DrCord
真的很奇怪...我会提供官方文档链接。谢谢! - Bastien Caudan
似乎它只解决了选择默认选项的问题,但当选择默认选项时,模型无法正确更新。请提供更新模型的解决方案。 - ali
当使用ng-repeat填充选项时,这对我并没有起作用。不过,这个答案可以:https://dev59.com/IWUo5IYBdhLWcg3wxB7T#31676786 - Chris Rae

5

就像这样:

<body ng-controller="MainCtrl">
  {{referenceNumber}}
    <select ng-model="referenceNumber">
            <option ng-selected="!referenceNumber">Default</option>
            <option ng-repeat="number in numbers track by $index" ng-value="number">{{number}}</option>
        </select>
  </body>

我认为ngSelected的主要作用之一是根据模型设置默认值。

joshkurz于2014年3月3日发表评论。

因此,在您的情况下,正确的方法是仅依赖ng-model。实现所需操作(预先选择选项)的正确方法如下:

<select ng-model="purchase.product" name="purchase.product" class="u-full-width" ng-options="product.id as product.name for product in products"></select>

Reference:

  1. http://plnkr.co/edit/xXq3b40nvqkjPlyCxZNG?p=preview
  2. https://github.com/angular/angular.js/issues/6528

5
<select ng-model="hour">
    <option ng-selected="hour == $index" ng-repeat="h in (((b=[]).length=24)&&b) track by $index" ng-bind="$index">{{h}}</option>
</select>

如果您想选择24小时制,请按照以下步骤进行。


2
ng-selected指令接受一个布尔值或导致true/false布尔结果的表达式。
只需要传递其值true或导致true的表达式即可使其工作。
它与<select>标记的ng-model无关。
以下是此行为的示例:
<select name="quarter" ng-model="Quarter" >
    <option value="1" >Q1</option>
    <option value="2" ng-selected="true">Q2</option>
    <option value="3">Q3</option>
    <option value="4">Q4</option>
</select>

这将使选项Q2成为默认选择。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接