亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

搜索
AngularJS教程 / 選擇

選擇

使用 ng-options 創(chuàng)建下拉框

如果您想在 AngularJS 中基于對象或數(shù)組創(chuàng)建下拉列表,應(yīng)該使用 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 指令來創(chuàng)建相同的下拉列表:

實例

<select>
  <option ng-repeat="x in names">{{x}}</option>
</select>
運行實例 ?

點擊 "運行實例" 按鈕查看在線實例

由于 ng-repeat 指令為數(shù)組中的每個項目重復(fù)一段 HTML 代碼,因此它可用于在下拉列表中創(chuàng)建選項,但是 ng-options 指令是專門為下拉列表填充選項而設(shè)計的。

應(yīng)該使用哪一個?

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

假設(shè)您有一個對象數(shù)組:

$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>
運行實例 ?

點擊 "運行實例" 按鈕查看在線實例

當(dāng)使用值作為對象時,使用 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>
運行實例 ?

點擊 "運行實例" 按鈕查看在線實例

當(dāng)所選值為對象時,它可以包含更多信息,并且您的應(yīng)用程序可以更加靈活。

我們將在本教程中使用 ng-options 指令。

作為對象的數(shù)據(jù)源

在前面的示例中,數(shù)據(jù)源是數(shù)組,但我們也可以使用對象。

假設(shè)您有一個帶有鍵值對的對象:

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

ng-options 屬性中的表達(dá)式對于對象來說略有不同:

實例

使用對象作為數(shù)據(jù)源,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>
運行實例 ?

點擊 "運行實例" 按鈕查看在線實例