如何选择ng工作?

Bru*_*ode 22 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>
Run Code Online (Sandbox Code Playgroud)

更改'Q1''Q2'使没有选作我的期望.现在,在ng-selected="Quarter=='Q1'"删除之前,不要选择Q1ng-selected="Quarter=='Q2"

跆拳道.这假设是如何工作的?

Bas*_*dan 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>
Run Code Online (Sandbox Code Playgroud)

看一下select指令文档.


小智 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>
Run Code Online (Sandbox Code Playgroud)

如果你想要24小时选择,你可以这样做.


Jul*_*ins 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>
Run Code Online (Sandbox Code Playgroud)

“我相信 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>
Run Code Online (Sandbox Code Playgroud)

参考:

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