AngularJS 下拉框
AngularJS 允许您基于数组或对象中的项目创建下拉列表。
使用 ng-options 创建下拉框
如果您想在 AngularJS 中基于对象或数组创建下拉列表,应该使用 ng-options 指令:
实例
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
</script>
ng-options 与 ng-repeat
您也可以使用 ng-repeat 指令来创建相同的下拉列表:
实例
<select>
<option ng-repeat="x in names">{{x}}</option>
</select>
由于 ng-repeat 指令为数组中的每个项目重复一段 HTML 代码,因此它可用于在下拉列表中创建选项,但是 ng-options 指令是专门为下拉列表填充选项而设计的。
应该使用哪一个?
您可以使用 ng-repeat 指令和 ng-options 指令:
假设您有一个对象数组:
$scope.cars = [
{model : "Ford Mustang", color : "red"},
{model : "Fiat 500", color : "white"},
{model : "Volvo XC90", color : "black"}
];
实例
使用 ng-repeat:
<select ng-model="selectedCar">
<option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
</select>
<h1>You selected: {{selectedCar}}</h1>
当使用值作为对象时,使用 ng-value 代替 value:
实例
将 ng-repeat 用作对象:
<select ng-model="selectedCar">
<option ng-repeat="x in cars" ng-value="{{x}}">{{x.model}}</option>
</select>
<h1>You selected a {{selectedCar.color}} {{selectedCar.model}}</h1>
实例
使用 ng-options:
<select ng-model="selectedCar" ng-options="x.model for x in cars">
</select>
<h1>You selected: {{selectedCar.model}}</h1>
<p>Its color is: {{selectedCar.color}}</p>
当所选值为对象时,它可以包含更多信息,并且您的应用程序可以更加灵活。
我们将在本教程中使用 ng-options 指令。
作为对象的数据源
在前面的示例中,数据源是数组,但我们也可以使用对象。
假设您有一个带有键值对的对象:
$scope.cars = {
car01 : "Ford",
car02 : "Fiat",
car03 : "Volvo"
};
ng-options 属性中的表达式对于对象来说略有不同:
实例
使用对象作为数据源,x 代表键,y 代表值:
<select ng-model="selectedCar" ng-options="x for (x, y) in cars">
</select>
<h1>You selected: {{selectedCar}}</h1>
所选的值将始终是键值对中的值。
键值对中的值也可以是对象:
实例
所选的值仍然将是键值对中的值,只是这次它是一个对象:
$scope.cars = {
car01 : {brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"}
};
下拉列表中的选项不必是键值对中的键,它也可以是值,或者是值对象的属性:
实例
<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars"> </select>