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

Default Option disappears after select non-empty option

本文关键字:选项 默认 消失 选择      更新时间:2023-09-26

我有一个简单的问题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>

角度控制器 :

    .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但这不起作用

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

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

使用此方法:

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