如何选择ng工作?

时间:2013-04-02 18:30:39

标签: angularjs

这是一个片段。按我的预期选择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'"在删除ng-selected="Quarter=='Q2"

之前不要选择Q1

WTF。这假设是如何工作的?

4 个答案:

答案 0 :(得分:18)

如果将ng-selected放在选项元素上,当ng-selected值为true时,将选择您的选项。在您的情况下,当Quarter等于Q1时,选择Q2选项。

如果要选择Quarter中传递的值,则必须将ng-selected放在select元素上:

<select name="quarter" ng-model="Quarter" ng-selected="Quarter"
        ng-options="Quarter for Quarter in Quarters" >
    {{Quarter}}
</select>

查看select directive documentation

答案 1 :(得分: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 :(得分:4)

像这样:

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

参考:

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

答案 3 :(得分:1)

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。