AngularJS Select(選擇框)
AngularJS 可以使用數組或對象創建一個下拉列表選項。
使用ng-options 創建選擇框
在AngularJS中我們可以使用ng-option指令來創建一個下拉列表,列表項通過對象和數組循環輸出,如下實例:
實例
< div ng-app= "myApp" ng-controller= "myCtrl" >
< select ng-model= "selectedName" ng-options= "x for x in names" >
< /select >
< /div >
< script >
< 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 = [ "Google" , "w3big" , "Taobao" ];
});
app.controller( 'myCtrl' , function ($scope) {
$scope.names = [ "Google" , "w3big" , "Taobao" ];
});
< /script >
嘗試一下»
ng-options 與ng-repeat
我們也可以使用ng-repeat指令來創建下拉列表:
ng-repeat指令是通過數組來循環HTML代碼來創建下拉列表,但ng-options指令更適合創建下拉列表,它有以下優勢:
使用ng-options的選項的一個對象,ng-repeat是一個字符串。
應該用哪個更好?
假設我們使用以下對象:
$scope.sites = [ {site : "Google", url : "http://www.google.com"}, {site : "w3big", url : "http://www.w3big.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 >
< 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 >
< /select >
< h1 >你選擇的是: {{selectedSite.site}} < /h1 >
< p >網址為: {{selectedSite.url}} < /p >
嘗試一下»
當選擇值是一個對象時,我們就可以獲取更多信息,應用也更靈活。
數據源為對象
前面實例我們使用了數組作為數據源,以下我們將數據對像作為數據源。
$scope.sites = { site01 : "Google", site02 : "w3big", site03 : "Taobao" };
ng-options使用對像有很大的不同,如下所示:
實例
使用對像作為數據源,x為鍵(key), y為值(value):
< select ng-model= "selectedSite" ng-options= " x for (x, y) in sites " >
< /select >
< h1 >你選擇的值是: {{selectedSite}} < /h1 >
< /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" }
};
car01 : {brand : "Ford" , model : "Mustang" , color : "red" },
car02 : {brand : "Fiat" , model : "500" , color : "white" },
car03 : {brand : "Volvo" , model : "XC90" , color : "black" }
};
嘗試一下»
在下拉菜單也可以不使用key -value對中的key ,直接使用對象的屬性: