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

我有这个代码。

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

当前回答

我认为,在包含'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 setSeletected="{{data.value}}">
      <option value="value1"> value1....
      <option value="value2"> value2....
       ......

在指令中,我创建了一个检查值的脚本,当angular填充它时,将该值设置为选中的选项。

 .directive('setSelected', function(){
    restrict: 'A',
    link: (scope, element, attrs){
     function setSel=(){
     //test if the value is defined if not try again if so run the command
       if (typeof attrs.setSelected=='undefined'){             
         window.setTimeout( function(){setSel()},300) 
       }else{
         element.find('[value="'+attrs.setSelected+'"]').prop('selected',true);          
       }
     }
    }

  setSel()

})

刚刚从coffescript中翻译了这个,如果不是洞的东西,至少它的jist是正确的。

这不是最简单的方法,但当值变化时就能完成

这对我很管用。

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

如果你想确保你的$scope。当你的视图初始化时,somethingHere的值不会被覆盖,你会想要合并(somethingHere = somethingHere || options[0].value) ng-init中的值,如下所示:

<select ng-model="somethingHere" 
        ng-init="somethingHere = somethingHere || options[0].value"
        ng-options="option.value as option.name for option in options">
</select>