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

我有这个代码。

<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="true",如下所示:

<select ng-model="myModel">
        <option value="a" ng-selected="true">A</option>
        <option value="b">B</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是正确的。

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

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

如果你想确保你的$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>

在我的情况下,我需要插入一个初始值,只告诉用户选择一个选项,所以,我喜欢下面的代码:

<select ...
    <option value="" ng-selected="selected">Select one option</option>
</select>

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

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