过去几周我一直在使用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而没有多重选择,它看起来很奇怪。


当前回答

我们可以使用CSS隐藏第一个选项,但它不会工作在IE 10, 11。最好的方法是使用Jquery删除该元素。此解决方案适用于chrome和IE10,11测试的主要浏览器

如果你使用的是angular,有时候使用setTimeout也可以

$scope.RemoveFirstOptionElement = function (element) {
    setTimeout(function () {
        $(element.children()[0]).remove();
    }, 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清除空选项

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

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

如果你使用ng-init你的模型来解决这个问题:

<select ng-model="foo" ng-app ng-init="foo='2'">

一个快速的解决方案:

select option:empty { display:none }

希望它能帮助到别人。理想情况下,选择的答案应该是方法,但如果这是不可能的,那么应该作为补丁工作。

我使用的是Angular 1.4x,我找到了这个例子,所以我用ng-init在select中设置初始值:

<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.id for item in items"></select>