AngularJS 下拉框

AngularJS 允许您基于数组或对象中的项目创建下拉列表。

使用 ng-options 创建下拉框

如果您想在 AngularJS 中基于对象或数组创建下拉列表,应该使用 ng-options 指令:

Example

<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>

Try It Yourself

ng-options 与 ng-repeat

您也可以使用 ng-repeat 指令来创建相同的下拉列表:

Example

<select>
  <option ng-repeat="x in names">{{x}}</option>
</select>

Try It Yourself

由于 ng-repeat 指令为数组中的每个项目重复一段 HTML 代码,因此它可用于在下拉列表中创建选项,但是 ng-options 指令是专门为下拉列表填充选项而设计的。

应该使用哪一个?

您可以使用 ng-repeat 指令和 ng-options 指令:

dashi a za a zai da zai object zu:

$scope.cars = [
  {model : "Ford Mustang", color : "red"},
  {model : "Fiat 500", color : "white"},
  {model : "Volvo XC90", color : "black"}
];

Example

shi yong ng-repeat:

<select ng-model="selectedCar">
  <option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
</select>
<h1>Ana za: {{selectedCar}}</h1>

Try It Yourself

dang shi yong ce za a wei object shi, shi yong ng-value dai huan value:

Example

jiang ng-repeat zu yong wei object:

<select ng-model="selectedCar">
  <option ng-repeat="x in cars" ng-value="{{x}}">{{x.model}}</option>
</select>
<h1>Ana za a {{selectedCar.color}} {{selectedCar.model}}</h1>

Try It Yourself

Example

shi yong ng-options:

<select ng-model="selectedCar" ng-options="x.model for x in cars">
</select>
<h1>Ana za: {{selectedCar.model}}</h1>
<p>Color na: {{selectedCar.color}}</p>

Try It Yourself

dang xuan ze ce za a zai object shi, ta ke yi bao han geng duo xin xi, qi ni de ying yong cheng neng geng jia ling huo.

women jiang zai ben jiao cheng zhong shi yong ng-options ming ling.

zai da zai data source

zai qian mian shi li, data source shi zu zu, dàn women ye neng shi yong object.

dashi a za a zai da zai key-value object:

$scope.cars = {
  car01 : "Ford",
  car02 : "Fiat",
  car03 : "Volvo"
};

ng-options expression na attribute na ga zai da zai object na ni you yi wei ben ben:

Example

a zai da zai data source,x wani:y wani:

<select ng-model="selectedCar" ng-options="x for (x, y) in cars">
</select>
<h1>Ana za: {{selectedCar}}</h1>

Try It Yourself

ana ce za a za zai kanji naValue.

kanji naValuebii da:

Example

ana ce za a zai zai kanji naValuethis time it is an object:

$scope.cars = {
  car01 : {brand : "Ford", model : "Mustang", color : "red"},
  car02 : {brand : "Fiat", model : "500", color : "white"},
  car03 : {brand : "Volvo", model : "XC90", color : "black"}
};

Try It Yourself

Options in the dropdown list do not have to be in the key-value pairKeywa ko iya zata kuma shi yadda, ko take, ko kuma halittuwar alamminin wuri:

Example

<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars">
</select>

Try It Yourself