繁体   English   中英

如何使用选择ng-options实现有效的null-option

[英]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'}];

现在,很容易使用ng-options构建选择以从categories进行选择,以将所选的category.id设置为person.category1person.category2

但是,当category1是必需的而category2仍然可以是有效的值时,我该怎么做呢?

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

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

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

编辑

我基于@Mistalis答案添加了一个Plunkr ,它显示了我想要实现的目标:每个选择都应具有一个禁用的占位符选项,并且应该支持一个“有效的null选项”。

您可以使用以下optionoption (空)添加到您的select

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

在Plunker上的演示


如果需要,可以在控制器categ.selected默认设置为null:

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

评论更新:

看来您无法在ng-options中硬编码2个选项,因此我建议您在控制器的categories中推送“ No category”选项:

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

请注意, noCat: 'true'会在第一次select不显示。

现在,您的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>

新柱塞

如果您需要使用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>

如果要使“ 选择类别”选项根本无法选择(如placholder),则将disabled属性添加到<option>

这是jsfiddle与您的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM