top
Loading...
AngularJS Select(選擇框)

AngularJS Select(選擇框)

AngularJS 可以使用數組或對象創建一個下拉列表選項。


使用 ng-options 創建選擇框

在 AngularJS 中我們可以使用 ng-option 指令來創建一個下拉列表,列表項通過對象和數組循環輸出,如下實例:

實例

<div ng-app="myApp" ng-controller="myCtrl"> <select ng-init="selectedName = names[0]" 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 = ["Google", "Runoob", "Taobao"]; }); </script>

嘗試一下 »

ng-init 設置默認選中值。


ng-options 與 ng-repeat

我們也可以使用ng-repeat 指令來創建下拉列表:

實例

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

嘗試一下 »

ng-repeat 指令是通過數組來循環 HTML 代碼來創建下拉列表,但 ng-options 指令更適合創建下拉列表,它有以下優勢:

使用 ng-options 的選項是一個對象, ng-repeat 是一個字符串。


應該用哪個更好?

假設我們使用以下對象:

$scope.sites = [
    {site : "Google", url : "http://www.google.com"},
    {site : "Runoob", url : "http://www.sharebody.com"},
    {site : "Taobao", url : "http://www.taobao.com"}
];

ng-repeat 有局限性,選擇的值是一個字符串:

實例

使用 ng-repeat:

<select ng-model="selectedSite">
<option ng-repeat="x in sites" value="{{x.url}}">{{x.site}}</option>
</select>

<h1>你選擇的是: {{selectedSite}}</h1>

嘗試一下 »

使用 ng-options 指令,選擇的值是一個對象:

實例

使用 ng-options:

<select ng-model="selectedSite" ng-options="x.site for x in sites">
</select>

<h1>你選擇的是: {{selectedSite.site}}</h1>
<p>網址為: {{selectedSite.url}}</p>

嘗試一下 »

當選擇值是一個對象時,我們就可以獲取更多信息,應用也更靈活。


數據源為對象

前面實例我們使用了數組作為數據源,以下我們將數據對象作為數據源。

$scope.sites = {
    site01 : "Google",
    site02 : "Runoob",
    site03 : "Taobao"
};

ng-options 使用對象有很大的不同,如下所示:

實例

使用對象作為數據源, x 為鍵(key), y 為值(value):

<select ng-model="selectedSite" ng-options="x for (x, y) in sites">
</select>

<h1>你選擇的值是: {{selectedSite}}</h1>

嘗試一下 »

你選擇的值為在 key-value 對中的 value

value 在 key-value 對中也可以是個對象:

實例

選擇的值在 key-value 對的 value 中, 這是它是一個對象:

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

嘗試一下 »

在下拉菜單也可以不使用 key-value 對中的 key , 直接使用對象的屬性:

實例

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

嘗試一下 »
北斗有巢氏 有巢氏北斗