![](/img/trans.png)
[英]How to auto select another option in angularjs using 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'}];
現在,很容易使用ng-options
構建選擇以從categories
進行選擇,以將所選的category.id
設置為person.category1
或person.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選項”。
您可以使用以下option
將option
(空)添加到您的select
:
<select ng-model="categ.selected" ng-options="c.name for c in categories">
<option value="">No category</option>
</select>
如果需要,可以在控制器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.