AngularJS select中ngOptions用法詳解

AngularJS select中ngOptions用法詳解

 

1、用法

ngOption針對不一樣類型的數據源有不一樣的用法,主要體如今數組和對象上。html

數組:前端

label for value in array 
select as label for value in array
label group by group for value in array
select as label group by group for value in array
select as label group by group for value in array track by trackexpr

對象:git

label for ( key , value ) in object
select as label for ( key , value ) in object
label group by group for ( key , value ) in object
select as label group by group for ( key , value ) in object
 
  

說明:github

array / object: 數據源的類型,有數組和對象兩種
value:迭代過程當中,引用數組的項或者對象的屬性值
key:迭代過程當中,引用對象的屬性名
label:選項顯示的標籤,用戶可看到的
select:結果綁定到ngModel中,若是沒有指定,則默認綁定value
group:group by的條件,表示按某條件進行分組
trackexpr:用於惟一肯定數組中的迭代項的表達式

2、實例

通用的js代碼:數組

 
    
複製代碼
<script>
    var MyModule = angular.module("MyModule",[]);
    MyModule.controller("Ctrl",["$scope", function($scope){
        $scope.colors = [
            {name:'black', shade:'dark'},
            {name:'white', shade:'light'},
            {name:'red', shade:'dark'},
            {name:'blue', shade:'dark'},
            {name:'yellow', shade:'light'}
        ];
        $scope.object = {
            dark: "black",
            light: "red",
            lai: "red"
        };
    }]);
</script>
複製代碼

label for value in array

html:微信

 
    
<select ng-model="myColor" ng-options="color.name for color in colors"></select>
 
   

效果:post

 

select as label for value in array

html:ui

<select ng-model="myColor" ng-options="color.shade as color.name for color in colors"></select>

效果:url

 

 


 label group by group for value in arrayspa

html:

<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors"></select>
效果:
 

 select as label group by group for value in array

html:

<select ng-model="myColor" ng-options="color.name as color.name group by color.shade for color in colors">

效果:

 

 select as label group by group for value in array track by trackexpr

html:

<select ng-model="myColor" ng-options="color.name for color in colors track by color.name">

效果:

 

 label for ( key , value ) in object

html:

<select ng-model="obj" ng-options="key for (key, value) in object"></select>

效果:

 

 select as label for ( key , value ) in object

html:

<select ng-model="obj" ng-options="key as key for (key, value) in object"></select>

效果:

 

 label group by group for ( key , value ) in object

html:

<select ng-model="obj" ng-options="key group by value for (key, value) in object"></select>

效果:

 

 select as label group by group for ( key , value ) in object

html:

<select ng-model="obj" ng-options="key as key group by value for (key, value) in object"></select>

效果:


 

Blog:http://www.laixiangran.cn

GitHub:https://github.com/laixiangran

Weibo:http://weibo.com/laixiangran

Email:laixiangran@163.com

QQ:1452446775

(微信公衆號-前端佈道-laixiangran_js)

 
分類:  AngularJS, Javascript
相關文章
相關標籤/搜索