我已经搜索了谷歌,在这个上面什么也找不到。

我有这个代码。

<select ng-model="somethingHere" 
        ng-options="option.value as option.name for option in options"
></select>

有这样的数据

options = [{
   name: 'Something Cool',
   value: 'something-cool-value'
}, {
   name: 'Something Else',
   value: 'something-else-value'
}];

输出是这样的。

<select ng-model="somethingHere"  
        ng-options="option.value as option.name for option in options" 
        class="ng-pristine ng-valid">

    <option value="?" selected="selected"></option>
    <option value="0">Something Cool</option>
    <option value="1">Something Else</option>
</select>

如何将数据中的第一个选项设置为默认值,从而得到这样的结果呢?

<select ng-model="somethingHere" ....>
    <option value="0" selected="selected">Something Cool</option>
    <option value="1">Something Else</option>
</select>

当前回答

我认为最简单的方法是

 ng-selected="$first"

其他回答

我认为,在包含'track by'之后,你可以在ng-options中使用它来得到你想要的东西,就像下面这样

 <select ng-model="somethingHere" ng-options="option.name for option in options track by option.value" ></select>

这种方法更好因为当你想用对象列表替换字符串列表时你只需要把这个改成

 <select ng-model="somethingHere" ng-options="object.name for option in options track by object.id" ></select>

这里当然是一个带有属性名和id的对象。请注意,'as'不能用这种方式来表示ng-options,因为它只会设置值,当您使用track by时,您将无法更改它

对于Ben Lesh的回答,应该有这样一条线

ng-init="somethingHere = somethingHere || options[0]" 

而不是

ng-init="somethingHere = somethingHere || options[0].value" 

也就是说,

<选择ng-model = " somethingHere " ng-init="somethingHere = somethingHere || options[0]" Ng-options ="option.name for options track by option.value"> < /选择>

根据您拥有的选项的数量,您可以将值放在一个数组中,并像这样自动填充选项

<select ng-model="somethingHere.values" ng-options="values for values in [5,4,3,2,1]">
   <option value="">Pick a Number</option>
</select>

这对我很管用。

<select ng-model="somethingHere" ng-init="somethingHere='Cool'">
    <option value="Cool">Something Cool</option>
    <option value="Else">Something Else</option>
</select>

如果你使用ng-options来渲染你的下拉列表,那么默认选择与ng-modal值相同的选项。 请看下面的例子:

<select ng-options="list.key as list.name for list in lists track by list.id" ng-model="selectedItem">

所以option有相同的list值。key和selectedItem是默认选择。