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


当前回答

在这里的众多答案中,我认为我应该转发对我有效的解决方案,并满足以下所有条件:

当ng-model是假的时提供一个占位符/提示符。——select region——" w. value="") 当ng-model值为假值时,用户打开options下拉菜单,则选择占位符(此处提到的其他解决方案使第一个选项显示为选中,这可能会产生误导) 允许用户取消选择有效值,实际上是再次选择假值/默认值

code

<select name="market_vertical" ng-model="vc.viewData.market_vertical"
    ng-options="opt as (opt | capitalizeFirst) for opt in vc.adminData.regions">

    <option ng-selected="true" value="">select a market vertical</option>
</select>

src

独创的q&a - https://stackoverflow.com/a/32880941/1121919

其他回答

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

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

这完全没问题

<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
    <option style="display:none" value=""></option>
</select>

它的工作方式是,这给了第一个选项显示之前选择的东西和显示:没有删除它从下拉菜单,所以如果你想要,你可以这样做

<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
    <option style="display:none" value="">select an option...</option>
</select>

这将在选择之前给你选择和选项,但一旦选择,它就会消失,不会在下拉列表中显示。

唯一对我有用的是在ng-options中使用track by,就像这样:

 <select class="dropdown" ng-model="selectedUserTable" ng-options="option.Id as option.Name for option in userTables track by option.Id">

也许对某人有用:

如果你想使用普通选项而不是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清除空选项

当你无法控制选项时,使用jQuery的刷任务解决方案

html:

<select id="selector" ng-select="selector" data-ng-init=init() >
...
</select>

js:

$scope.init = function () {
    jQuery('#selector option:first').remove();
    $scope.selector=jQuery('#selector option:first').val();
}