?
Ce document utilise Manuel du site Web PHP chinois Libérer
帶有angular數(shù)據(jù)綁定功能的HTML SELECT
元素。
ngOptions
ngOptions
屬性可用于動(dòng)態(tài)生成<option>
元素列表,當(dāng)對(duì)<select>
元素使用數(shù)組,或者是 ngOptions
可解析的表達(dá)式計(jì)算得到的對(duì)象。
當(dāng)<select>
菜單中的一項(xiàng)被選中時(shí),數(shù)組元素或?qū)ο髮傩宰鳛楸贿x中的選項(xiàng)綁定到模型的 ngModel
指令。
ngModel
通過引用比較,而非值比較。這在使用對(duì)象數(shù)組 綁定時(shí)很重要。參見示例in this jsfiddle.此外,設(shè)置為空字符串值的單個(gè)硬編碼的<option>
元素可以嵌套到 <select>
元素中。這個(gè)元素將表現(xiàn)為null
或 "not selected"選項(xiàng)。參見下面的示例演示。
ngOptions
為<option>
提供了一個(gè)迭代器工廠用于替代 ngRepeat,在你想讓 select
模型綁定到非字符串值時(shí)。這是因?yàn)橐粋€(gè)選項(xiàng)元素只能被綁定到一個(gè)字符串值上。<select
ng-model=""
[name=""]
[required=""]
[ng-required=""]
[ng-options=""]>
...
</select>
參數(shù) | 類型 | 詳述 |
---|---|---|
ngModel | string | 聲明用于數(shù)據(jù)綁定的Angular表達(dá)式。 |
name (可選)
|
string | 發(fā)布到表單下的控件的屬性名稱。 |
required
(可選)
|
string | 控件只有輸入值才被認(rèn)為有效。 |
ngRequired
(可選)
|
string | 當(dāng)ngRequired表達(dá)式等于true時(shí),添加 |
ngOptions
(可選)
|
comprehension_expression |
下列形式之一:
這里:
|
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', Function($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.myColor = $scope.colors[2]; // red
}]);
</script>
<div ng-controller="ExampleController">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="myColor" ng-options="color.name for color in colors">
<option value="">-- choose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
</select><br/>
Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:myColor} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':myColor.name}">
</div>
</div>
it('should check ng-options', Function() {
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
element.all(by.model('myColor')).first().click();
element.all(by.css('select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
element(by.css('.nullable select[ng-model="myColor"]')).click();
element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');});