AngularJS orderBy 使用要點總結:
1,書寫格式
基本應用格式為:
ng-repeat="item in itemList | orderBy:p1:p2"
參數p1可以是字段名或自定義函數,p2指是否逆序,默認是false
舉例:
假設$scope中有
$scope.itemList=[{id:201,name:'abc',amount:100},{id:100,name:'zdb',amount:100},
{id:10,name:'xxx',amount:200},{id:80,name:'231',amount:1020},
{id:50,name:'ppp',amount:20},{id:1,name:'hhh',amount:1100}];
按照id,倒排序
ng-repeat="item in itemList | orderBy:'id':true"
2,自定義排序:
controller中設置自定義函數,函數接受參數為當前的item,需要返回一個數值代表該item的順序
$scope.orderIt=function(item){ if(item.name.indexOf('h')===0)return 0; return 1; };
使用方法:
ng-repeat="item in itemList | orderBy:orderIt"
3,多字段排序:
如果單個字段排序不能滿足需求,那就要祭出絕活了!orderBy還支持多字段排序,方法如下
ng-repeat="item in itemList | orderBy:[orderIt,'name','-amount']
沒錯,第一個參數傳遞數組,可以是自定義函數或字段名,字段名前面加“-”,代表倒排序。