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>

親自試一試