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


当前回答

这个解决方案对我来说很有效:

<select ng-model="mymodel">    
   <option ng-value="''" style="display:none;" selected>Country</option>
   <option value="US">USA</option>
</select>

其他回答

我使用的是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>

如果需要初始值,请参阅@pkozlowski。开源的答案,供你参考,它也可以在视图中(而不是在控制器中)使用ng-init实现:

<select ng-model="form.type" required="required" ng-init="form.type='bug'"
  ng-options="option.value as option.name for option in typeOptions" >
</select>

如果你不想要一个初始值,“一个硬编码的元素,将值设置为空字符串,可以嵌套到元素中。该元素将表示null或“未选中”选项:

<select ng-model="form.type" required="required"
  ng-options="option.value as option.name for option in typeOptions" >
    <option style="display:none" value="">select a type</option>
</select>

简单的解决方案

<select ng-model='form.type' required><options>
<option ng-repeat="tp in typeOptions" ng-selected="    
{{form.type==tp.value?true:false}}" value="{{tp.value}}">{{tp.name}}</option>

这完全没问题

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

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

参考angularjs文档中的例子如何克服这些问题。

点击这里的文档链接 查找“通过ngModel解析/格式化将select绑定到非字符串值” 你可以看到,指令convertToNumber解决了这个问题。

这对我很管用。也可以看到它是如何工作在这里