AngularJS select中ngOptions用法詳解

Claire_ljy發表於2020-04-04

一、用法

ngOption針對不同型別的資料來源有不同的用法,主要體現在陣列和物件上。

陣列:

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

物件:

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

說明:

array / object: 資料來源的型別,有陣列和物件兩種
value:迭代過程中,引用陣列的項或者物件的屬性值
key:迭代過程中,引用物件的屬性名
label:選項顯示的標籤,使用者可看到的
select:結果繫結到ngModel中,如果沒有指定,則預設繫結value
group:group by的條件,表示按某條件進行分組
trackexpr:用於唯一確定陣列中的迭代項的表示式

二、例項

通用的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>

效果:

 

select as label for value in array

html:

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

效果:

 

 


 label group by group for value in array

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>

效果:


 

轉載於:https://www.cnblogs.com/laixiangran/p/4956751.html

相關文章