AngularJS下拉選擇框(select)

AngularJS Select(選擇框)

AngularJS 能夠使用數組或對象建立一個下拉列表選項。javascript

使用 ng-options 建立選擇框

在 AngularJS 中咱們能夠使用 ng-option 指令來建立一個下拉列表,列表項經過對象和數組循環輸出,以下實例:html

<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 設置默認選中值。java

ng-options 與 ng-repeat

咱們也能夠使用ng-repeat 指令來建立下拉列表:數組

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

ng-repeat 指令是經過數組來循環 HTML 代碼來建立下拉列表,但 ng-options 指令更適合建立下拉列表,它有如下優點:app

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

應該用哪一個更好?

假設咱們使用如下對象:url

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

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

使用 ng-repeat:code

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

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

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

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

另外一種使用方式,在沒法根據ng-model自動選擇對應的項時能夠使用這個方式:

<label class="item item-input item-select">
          <span class="input-label">人員分類</span>
          <select ng-model="search.stafftype">
            <option value="{{$index}}" ng-repeat="t in staffTypes" ng-selected="number==$index">{{t}}</option>         
          </select>
</label>
相關文章
相關標籤/搜索