?
Dieses Dokument verwendet PHP-Handbuch für chinesische Websites Freigeben
帶有angular數據綁定功能的HTML SELECT
元素。
ngOptions
ngOptions
屬性可用于動態(tài)生成<option>
元素列表,當對<select>
元素使用數組,或者是 ngOptions
可解析的表達式計算得到的對象。
當<select>
菜單中的一項被選中時,數組元素或對象屬性作為被選中的選項綁定到模型的 ngModel
指令。
ngModel
通過引用比較,而非值比較。這在使用對象數組 綁定時很重要。參見示例in this jsfiddle.此外,設置為空字符串值的單個硬編碼的<option>
元素可以嵌套到 <select>
元素中。這個元素將表現為null
或 "not selected"選項。參見下面的示例演示。
ngOptions
為<option>
提供了一個迭代器工廠用于替代 ngRepeat,在你想讓 select
模型綁定到非字符串值時。這是因為一個選項元素只能被綁定到一個字符串值上。<select
ng-model=""
[name=""]
[required=""]
[ng-required=""]
[ng-options=""]>
...
</select>
參數 | 類型 | 詳述 |
---|---|---|
ngModel | string | 聲明用于數據綁定的Angular表達式。 |
name (可選)
|
string | 發(fā)布到表單下的控件的屬性名稱。 |
required
(可選)
|
string | 控件只有輸入值才被認為有效。 |
ngRequired
(可選)
|
string | 當ngRequired表達式等于true時,添加 |
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');});