为什么AngularJS在select中包含一个空选项? [英] Why does AngularJS include an empty option in select?

查看:116
本文介绍了为什么AngularJS在select中包含一个空选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几周里,我一直在使用AngularJS,而让我感到困扰的一件事是,即使尝试了

I've been working with AngularJS for the last few weeks, and the one thing which is really bothering me is that even after trying all permutations or the configuration defined in the specification at http://docs.angularjs.org/api/ng.directive:select, I still get an empty option as the first child of select element.

这是玉:

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:

Finally, here's the HTML which gets generated:

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

我该怎么做才能摆脱它?

What do I need to do to get rid of it?

P.S .:事情也不需要这个,但是如果您使用select2而没有多重选择,那看起来就很奇怪了.

P.S.: Things work without this as well, but it just looks odd if you use select2 without multiple selection.

推荐答案

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

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

如果要摆脱空选项,只需在控制器中选择一个初始值,例如:

If you want to get rid of the empty option just select an initial value in your controller, something like:

$scope.form.type = $scope.typeOptions[0].value;

这是jsFiddle: http://jsfiddle.net/MTfRD/3/

Here is the jsFiddle: http://jsfiddle.net/MTfRD/3/

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

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

这篇关于为什么AngularJS在select中包含一个空选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆