选择非空选项后,默认选项消失

时间:2016-04-26 10:21:17

标签: javascript angularjs select options

我有一个简单的问题示例JSFiddle

开始时我有空/默认选项,但是当我从下拉列表中选择其他内容时,此选项会消失。

选择后如何保留此选项?

 <label for="mySelect">Make a choice:</label>
 <select name="mySelect" id="mySelect"
      ng-options="option.name for option in data.availableOptions"
      ng-model="data.selectedOption"></select>

Angular-controller:

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

我已尝试使用ng-init将默认选项设为null,但这样做无法运作

2 个答案:

答案 0 :(得分:2)

请在select元素中添加空选项元素并检查。

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

答案 1 :(得分:0)

使用这种方法:

<强> HTML

<div 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.id as option.name for option in data.availableOptions"
      ng-model="data.selectedOption"></select>
  </form>
  <hr>
  <tt>option = {{data.selectedOption}}</tt><br/>
</div>

<强> AngulerJS

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: '2' //This sets the default value of the select in the ui
    };

}]);