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

我有这个代码。

<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 ...
    <option value="" ng-selected="selected">Select one option</option>
</select>

当我尝试一个空字符串(null)的值!=的选项时,该选项被angular取代,但是,当放置一个这样的选项(空值)时,选择出现这个选项。

抱歉我的英语不好,我希望我能在这方面有所帮助。

其他回答

简单地使用ng-selected="true",如下所示:

<select ng-model="myModel">
        <option value="a" ng-selected="true">A</option>
        <option value="b">B</option>
</select>

我认为最简单的方法是

 ng-selected="$first"
    <!--
    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>

我会在控制器中设置模型。然后选择将默认为该值。例: html:

<select ng-options="..." ng-model="selectedItem">

Angular控制器(使用资源):

myResource.items(function(items){
  $scope.items=items;
  if(items.length>0){
     $scope.selectedItem= items[0];
//if you want the first. Could be from config whatever
  }
});

使用下面的代码填充从您的模型中选择的选项。

<select id="roomForListing" ng-model="selectedRoom.roomName" >

<option ng-repeat="room in roomList" title="{{room.roomName}}" ng-selected="{{room.roomName == selectedRoom.roomName}}" value="{{room.roomName}}">{{room.roomName}}</option>

</select>