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

我有这个代码。

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

当前回答

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

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

其他回答

我的解决方案是使用html硬编码我的默认选项。像这样:

HAML:

%select{'ng-model' => 'province', 'ng-options' => "province as province for province in summary.provinces", 'chosen' => "chosen-select", 'data-placeholder' => "BC & ON"}
  %option{:value => "", :selected => "selected"}
    BC &amp; ON

在HTML中:

<select ng-model="province" ng-options="province as province for province in summary.provinces" chosen="chosen-select" data-placeholder="BC & ON">
  <option value="" selected="selected">BC &amp; ON</option>
</select>

我想我的默认选项从我的api返回所有的值,这就是为什么我有一个空白值。也请原谅我的笨手笨脚。我知道这不是对OP问题的直接回答,但人们在谷歌上找到了这个。希望这能帮助到其他人。

这对我很管用。

<select ng-model="somethingHere" ng-init="somethingHere='Cool'">
    <option value="Cool">Something Cool</option>
    <option value="Else">Something Else</option>
</select>
    <!--
    Using following solution you can set initial 
default value at controller as well as after change option selected value shown as default.
    -->
    <script type="text/javascript">
      function myCtrl($scope)
        {
          //...
            $scope.myModel=Initial Default Value; //set default value as required
          //..
        }
    </script>
    <select ng-model="myModel" 
                ng-init="myModel= myModel"
                ng-options="option.value as option.name for option in options">
        </select>

这对我很有用

ng-selected="true" 

试试这个:

HTML

<select 
    ng-model="selectedOption" 
    ng-options="option.name for option in options">
</select>

Javascript

function Ctrl($scope) {
    $scope.options = [
        {
          name: 'Something Cool',
          value: 'something-cool-value'
        }, 
        {
          name: 'Something Else',
          value: 'something-else-value'
        }
    ];

    $scope.selectedOption = $scope.options[0];
}

砰砰作响。

如果您真的想设置将绑定到模型的值,那么将ng-options属性更改为

ng-options="option.value as option.name for option in options"

和Javascript

...
$scope.selectedOption = $scope.options[0].value;

考虑到上述情况,这里又一个普伦克。