ng-select默认为不工作

时间:2017-08-28 14:31:18

标签: angularjs angularjs-ng-repeat angularjs-select

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

我的问题是它不起作用,而且选择总是空白。

这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

使用默认<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>

答案 1 :(得分:1)

  

当传递给ng-options的一组选项中不存在ng-model引用的值时,将生成空选项。这可以防止意外的模型选择:AngularJS可以看到初始模型在选项集中未定义或不定义,并且不希望自己决定模型值。

简而言之:空选项意味着没有选择有效模型(有效我的意思是:来自选项集)。您需要选择一个有效的模型值来摆脱这个空选项。

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