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