ng-select 的默认值不工作

Default for ng-select not working

我有一个使用 select 的表格。我正在尝试设置一个我想禁用的默认值,因此下拉列表将显示“-- select state --”作为第一个选项,并将强制用户进行 select离子.

我的问题是它不工作,select 开始时总是空白。

这是我的代码:

    <select ng-model="contactEditCtrl.addressData.state" style="width: 50%;">
      <option ng-disabled="$index === 1"  ng-selected="true">--Select State--</option>
      <option value="{{state.abbreviation}}" ng-repeat="state in contactEditCtrl.states">{{state.name}}</option>
    </select>

勾选默认 <option>ng-options:

 <select ng-model="contactEditCtrl.addressData.state" 
         ng-options="state.name as state.name for state in contactEditCtrl.states" >
      <option value="" ng-disabled="true">-- select state --</option>
</select>

Demo fiddle

它将被转换为:

<select ng-model="addressData.state" style="width: 50%;" 
        ng-options="state.name as state.name for state in states" class="ng-valid ng-dirty">
    <option value="" ng-disabled="true" class="" disabled="disabled">-- select state --</option>
    <option value="0">CCCCC</option>
    <option value="1">QQQQQQ</option>
</select>

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

简而言之:空选项意味着没有有效模型是 selected(我所说的有效是指:来自选项集)。您需要 select 一个有效的模型值才能摆脱这个空选项。

取自here

所以我建议这样写。

var app = angular.module('myApp', []);

// Register MyController object to this app
app.controller('MyController', function MyController($scope) {
    this.addressData = {state: "--Select State--"};
    this.states = [{abbreviation: 'a', name:'ant'}, {abbreviation: 'b', name:'asd'}, {abbreviation: 'b', name:'asd2'}]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app='myApp' ng-controller='MyController as contactEditCtrl'>
    <select ng-model="contactEditCtrl.addressData.state" style="width: 50%;">
      <option value="--Select State--">--Select State--</option>
      <option ng-value="state.abbreviation" ng-repeat="state in contactEditCtrl.states">{{state.name}}</option>
    </select>
</div>