过去几周我一直在使用AngularJS,有一件事真的困扰着我,即使在http://docs.angularjs.org/api/ng.directive:select的规范中尝试了所有的排列或配置,我仍然得到一个空选项作为select元素的第一子元素。

这是玉:

select.span9(ng-model='form.type', required, ng-options='option.value as option.name for option in typeOptions');

下面是控制器:

$scope.typeOptions = [
    { name: 'Feature', value: 'feature' },
    { name: 'Bug', value: 'bug' },
    { name: 'Enhancement', value: 'enhancement' }
];

最后,这里是生成的HTML:

<select ng-model="form.type" required="required" ng-options="option.value as option.name for option in typeOptions" class="span9 ng-pristine ng-invalid ng-invalid-required">
    <option value="?" selected="selected"></option>
    <option value="0">Feature</option>
    <option value="1">Bug</option>
    <option value="2">Enhancement</option>
</select>

我需要做什么才能摆脱它?

附注:没有这个也可以工作,但是如果使用select2而没有多重选择,它看起来很奇怪。


当前回答

一个简单的解决方案是设置一个空值的选项“”我发现这消除了额外的未定义选项。

其他回答

在你的控制器中试试这个,按相同的顺序:

$scope.typeOptions = [
    { name: 'Feature', value: 'feature' }, 
    { name: 'Bug', value: 'bug' }, 
    { name: 'Enhancement', value: 'enhancement' }
];
$scope.form.type = $scope.typeOptions[0];

也许对某人有用:

如果你想使用普通选项而不是ng-options,你可以这样做:

<select ng-model="sortorder" ng-init="sortorder='publish_date'">
  <option value="publish_date">Ascending</option>
  <option value="-publish_date">Descending</option>
</select>

内联设置模型。使用ng-init清除空选项

下面是解决方案:

对于如下示例数据:

financeRef.pageCount = [{listCount:10,listName:modelStrings.COMMON_TEN_PAGE},    
{listCount:25,listName:modelStrings.COMMON_TWENTYFIVE_PAGE},
{listCount:50,listName:modelStrings.COMMON_FIFTY_PAGE}];

选择选项应该像这样:-

<select ng-model="financeRef.financeLimit" ng-change="financeRef.updateRecords(1)" 
class="perPageCount" ng-show="financeRef.showTable" ng-init="financeRef.financeLimit=10"
ng-options="value.listCount as value.listName for  value in financeRef.pageCount"
></select>

重点是当我们写值的时候。listCount作为值。listName,它自动在value中填充文本。listName,但所选选项的值为value。虽然我的值显示正常的0,1,2 ..等等!!

在我的例子中,是financeRef。financeLimit实际上是在获取值。listCount,我可以动态地在控制器中进行操作。

当ng-model属性未定义时,ng-model将创建空选项值。如果我们将object赋值给ng-model,就可以避免这种情况

例子

角编码

$scope.collections = [
    { name: 'Feature', value: 'feature' }, 
    { name: 'Bug', value: 'bug' }, 
    { name: 'Enhancement', value: 'enhancement'}
];

$scope.selectedOption = $scope.collections[0];


<select class='form-control' data-ng-model='selectedOption' data-ng-options='item as item.name for item in collections'></select>

重要提示:

为数组对象赋值,如$scope。集合[0]或$scope。集合[1]到ng-model,不使用对象属性。如果你从服务器获取选择选项值,使用回调函数,将对象分配给ng-model

来自Angular文档的说明

注意:ngModel比较的是引用,而不是值。当绑定到对象数组时,这很重要。参见示例http://jsfiddle.net/qWzTb/

我试了很多次终于找到了。

一个简单的解决方案是设置一个空值的选项“”我发现这消除了额外的未定义选项。