如何在Angular.js选择框中有一个默认选项

问题描述 投票:295回答:24

我搜索过谷歌,找不到任何相关内容。

我有这个代码。

<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>
javascript angularjs html-select
24个回答
351
投票

你可以像这样简单地使用ng-init

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

10
投票

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

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

当我尝试使用值!=空字符串(null)的选项时,该选项被angular替换,但是,当放置一个类似的选项(带有空值)时,选择将显示此选项。

对不起我的英语不好,我希望我能帮忙解决这个问题。


8
投票

selectngOptions一起使用并设置默认值:

有关更多ngOptions用法示例,请参阅ngOptions文档。

angular.module('defaultValueSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ],
    selectedOption: {id: '2', name: 'Option B'} //This sets the default value of the select in the ui
    };
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<body ng-app="defaultValueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="mySelect">Make a choice:</label>
    <select name="mySelect" id="mySelect"
      ng-options="option.name for option in data.availableOptions track by option.id"
      ng-model="data.selectedOption"></select>
  </form>
  <hr>
  <tt>option = {{data.selectedOption}}</tt><br/>
</div>

plnkr.co

Official documentation关于带有角度数据绑定的HTML SELECT元素。

通过select解析/格式化将ngModel绑定到非字符串值:

(function(angular) {
  'use strict';
angular.module('nonStringSelect', [])
  .run(function($rootScope) {
    $rootScope.model = { id: 2 };
  })
  .directive('convertToNumber', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        ngModel.$parsers.push(function(val) {
          return parseInt(val, 10);
        });
        ngModel.$formatters.push(function(val) {
          return '' + val;
        });
      }
    };
  });
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script>
<body ng-app="nonStringSelect">
  <select ng-model="model.id" convert-to-number>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
{{ model }}
</body>

plnkr.co

其他例子:

angular.module('defaultValueSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.availableOptions = [
     { name: 'Apple', value: 'apple' }, 
     { name: 'Banana', value: 'banana' }, 
     { name: 'Kiwi', value: 'kiwi' }
   ];
   $scope.data = {selectedOption : $scope.availableOptions[1].value};
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<body ng-app="defaultValueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <select ng-model="data.selectedOption" required ng-options="option.value as option.name for option in availableOptions"></select>
  </form>  
  </div>
</body>

jsfiddle


4
投票

这对我有用。

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

3
投票

在我的情况下,因为默认情况因表格中的不同情况而异。我在select标签中添加了一个自定义属性。

 <select setSeletected="{{data.value}}">
      <option value="value1"> value1....
      <option value="value2"> value2....
       ......

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

 .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()

})

刚从coffeescript中翻译过来,至少它的主旨是正确的,如果不是洞的话。

这不是最简单的方法,但在价值变化时完成


3
投票

在回应Ben Lesh's answer时,应该有这条​​线

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

代替

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

那是,

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

3
投票

只需使用ng-selected="true"如下:

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

2
投票

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

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

角度控制器(使用资源):

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
  }
});

1
投票

如果你使用ng-options渲染你下降,那么option具有与ng-modal相同的值,默认选择。考虑这个例子:

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

因此默认选择具有相同list.keyselectedItem值的选项。


1
投票

这对我有用

ng-selected="true" 

1
投票

如果你有一些东西而不是只是初始化日期部分,你可以通过在控制器中声明它来使用ng-init(),并在HTML的顶部使用它。此函数将像控制器的构造函数一样工作,您可以在那里启动变量。

angular.module('myApp', [])
 .controller('myController', ['$scope', ($scope) => {
   $scope.allOptions = [
     { name: 'Apple', value: 'apple' }, 
     { name: 'Banana', value: 'banana' }
   ];
   $scope.myInit = () => {
      $scope.userSelected = 'apple'
      // Other initiations can goes here..
   }
}]);


<body ng-app="myApp">
  <div ng-controller="myController" ng-init="init()">
    <select ng-model="userSelected" ng-options="option.value as option.name for option in allOptions"></select>
   </div>
</body>

228
投票

如果你想确保你的视图初始化时你的$scope.somethingHere值没有被覆盖,你需要在你的ng-init中合并(somethingHere = somethingHere || options[0].value)这样的值:

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

0
投票

我需要默认的“请选择”才能取消选择。我还需要能够有条件地设置默认选择的选项。

我通过以下简单方式实现了这一点:JS代码://翻转这两个来测试选定的默认值或没有默认默认值“请选择”文本//$scope.defaultOption = 0; $ scope.defaultOption = {key:'3',value:'Option 3'};

$scope.options = [
   { key: '1', value: 'Option 1' },
   { key: '2', value: 'Option 2' },
   { key: '3', value: 'Option 3' },
   { key: '4', value: 'Option 4' }
];

getOptions();

function getOptions(){
    if ($scope.defaultOption != 0)
    { $scope.options.selectedOption = $scope.defaultOption; }
}

HTML:

<select name="OptionSelect" id="OptionSelect" ng-model="options.selectedOption" ng-options="item.value for item in options track by item.key">
<option value="" disabled selected style="display: none;"> -- Please Select -- </option>
</select>
<h1>You selected: {{options.selectedOption.key}}</h1>         

我希望这有助于其他有类似要求的人。

“请选择”是通过Joffrey Outtier的回答here完成的。


0
投票
    <!--
    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>

0
投票

在角度控制器中尝试这个...

$ somethingHere = {name:'Something Cool'};

您可以设置一个值,但是您使用的是复杂类型,而angular将搜索要在视图中设置的键/值。

并且,如果不起作用,请尝试以下操作:ng-options =“option.value as option.name for options in option track by option.name”


-1
投票

我认为最简单的方法是

 ng-selected="$first"

-4
投票

最简单的方法(更新)

Explained here https://stackoverflow.com/a/37962911/5902146

69
投票

试试这个:

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];
}

Plunker here

如果您确实要设置将绑定到模型的值,请将ng-options属性更改为

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

和Javascript到

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

考虑到上述情况,另一个Plunker here


38
投票

只有一个answer by Srivathsa Harish Venkataramana提到track by,这确实是一个解决方案!

下面是一个关于如何在select track by中使用ng-options的Plunker(链接如下)的示例:

<select ng-model="selectedCity"
        ng-options="city as city.name for city in cities track by city.id">
  <option value="">-- Select City --</option>
</select>

如果selectedCity是在角度范围内定义的,并且它的id属性与id列表中任何city的任何cities具有相同的值,则它将在加载时自动选择。

这是Plunker:http://plnkr.co/edit/1EVs7R20pCffewrG0EmI?p=preview

有关更多详细信息,请参阅源文档:https://code.angularjs.org/1.3.15/docs/api/ng/directive/select


33
投票

我认为,在包含'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>

其中somethingHere是一个具有属性名称和id的对象,当然。请注意,'as'不是以这种方式表达ng-options,因为它只会设置值,当你使用track by时你将无法改变它


22
投票

接受的答案使用ng-init,但document说如果可能的话避免使用ng-init。

ngInpe的唯一合适用途是用于别名ngRepeat的特殊属性,如下面的演示所示。除了这种情况,您应该使用控制器而不是ngInit来初始化作用域上的值。

您也可以使用ng-repeat而不是ng-options作为选择。使用ng-repeat,您可以使用ng-selectedng-repeat特殊属性。即$ index,$ odd,$甚至无需任何编码即可完成这项工作。

$first是ng-repeat特殊属性之一。

  <select ng-model="foo">
    <option ng-selected="$first" ng-repeat="(id,value) in myOptions" value="{{id}}">
      {{value}}
    </option>
  </select>

----------------------编辑---------------- 虽然这有效,但我更喜欢@ mik-t的答案当你知道选择什么值时,https://stackoverflow.com/a/29564802/454252,它使用track-byng-options而不使用ng-initng-repeat

只有在必须选择第一项而不知道要选择什么值时才应使用此答案。例如,我将其用于自动完成,这需要始终选择第一项。


16
投票

我的解决方案是使用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

在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返回所有值,这就是为什么我有一个空值。也请原谅我的haml。我知道这不是OP问题的直接答案,但人们在Google上发现了这一点。希望这有助于其他人。


14
投票

使用以下代码填充模型中的选定选项。

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

10
投票

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

<select ng-model="somethingHere.values" ng-options="values for values in [5,4,3,2,1]">
   <option value="">Pick a Number</option>
</select>
© www.soinside.com 2019 - 2024. All rights reserved.