如何使用 select ng-options 实现有效的空选项

How to achieve a valid null-option with select ng-options

这里有几个关于这个主题的问题和答案,但我找不到适合我的情况的解决方案。

想象一下我有这样一个对象

$scope.person = {name: 'Peter', category1: null, category2: null};

在另一个变量中,我通过 $resource 调用收到类别列表,结果如下:

$scope.categories = [{id:1, name:'Supplier'}, {id:2, name:'Customer'}];

现在可以轻松构建 select 和 ng-options 以从 categories 中选择 selected category.idperson.category1person.category2.

但是,如果 category1 是强制性的,而 category2 仍然可以是有效的 null 值,我该怎么做呢?

所以基本上我现在正在寻找的是两个 selects 具有以下选项:

//Select1
- Select Category1 (disabled)
- Customer (value: 1)
- Supplier (value: 2)

//Select2
- Select Category2 (disabled)
- No Category (value: null)
- Customer (value: 1)
- Supplier (value: 2)

编辑

我添加了一个 Plunkr based on ,它显示了我想要实现的目标:每个 select 应该有一个禁用的占位符选项并且应该支持 "valid null option".

您可以使用以下内容将 option (null) 添加到您的 select

<select ng-model="categ.selected" ng-options="c.name for c in categories">
    <option value="">No category</option>
</select>

Demo on Plunker


如果需要,

categ.selected 可以在您的控制器中默认设置为空:

$scope.categ = {"selected": null};

评论更新:

看来你不能在 ng-options 中 hard-code 2 个选项,所以我建议你在你的控制器中推 categories 中的 "No category" 选项:

$scope.categories.push({id:null, name:'No category', noCat:'true'});

注意第一个select不显示的noCat: 'true'

现在你的 HTML 变成了:

<select ng-model="person.category1" 
        ng-options="c.id as c.name for c in categories | filter: {noCat: '!true'}">
    <option value="" disabled>Select Category 1</option>
</select>
<select ng-model="person.category2" ng-options="c.id as c.name for c in categories">
    <option value="" disabled>Select Category 2</option>
</select>

New Plunker

如果你需要用angular的表单控制器验证表单,你不能使用空值,它不会被视为有效。您必须改用 (int)0

  <select ng-model="person.category1" ng-options="category.id as category.name for category in categories | filter: {id: '!' + 0}" required>
    <option value="">Select Category 1</option>
  </select>
  <select placeholder="Select Category 2" ng-model="person.category2" ng-options="category.id as category.name for category in categories" required>
    <option value="">Select Category 2</option>
  </select>

如果你想让 Select 类别 选项对 select 根本不可用(就像一个占位符),然后添加 disabled属性为<option>

这是jsfiddle你的例子。