AngularJS深度orderBy排序:如何实现多层级自定义排序逻辑?
实现方案
实现思路
- 给自定义排序的维度提前定义权重映射,把非数值的排序规则转化为可比较的数值
- 利用AngularJS
orderBy过滤器支持传入自定义排序函数的特性,函数返回一个按优先级排列的排序维度数组,即可自动完成多层级排序
完整代码实现
控制器逻辑
// 定义各维度排序权重,数值越小排序越靠前 const stateWeightMap = { 'Initial': 1, 'Ongoing': 2, 'InReview': 3, 'Resolved': 4 } const priorityWeightMap = { 'P1': 1, 'P2': 2, 'P3': 3 } // 自定义排序函数 $scope.Custom_order = function(incident) { // 按优先级从高到低返回排序维度数组,orderBy会依次按数组元素排序 return [ // 第一层:State自定义排序,异常值默认排在最后 stateWeightMap[incident.State] || 99, // 第二层:Priority优先级排序,不在P1-P3范围内的默认排在最后 priorityWeightMap[incident.Priority] || 99, // 第三层:按开始日期升序,时间越早时间戳数值越小排越靠前 new Date(incident.Start_date).getTime() ] } // 原有Incidents数组保持不变即可 $scope.Incidents= [{ Start_date: "2021-12-01 09:20:00", State: "Initial", Priority: "P1" },{ Start_date: "2021-11-01 07:20:00", State: "Ongoing", Priority: "P2" },{ Start_date: "2021-10-01 05:20:00", State: "Resolved", Priority: "P3" },{ Start_date: "2021-12-01 09:48:00", State: "Ongoing", Priority: "coach" },{ Start_date: "2021-11-20 06:55:00", State: "InReview", Priority: "P1" },{ Start_date: "2021-08-01 09:20:00", State: "InReview", Priority: "P2" }];
模板修正
原有模板存在两处小错误:orderBy 参数缺少引号、显示字段重复写了Priority,修正后如下:
<div ng-repeat="incident in Incidents | orderBy:Custom_order"> <div>{{incident.State}} - {{incident.Priority}} - {{incident.Start_date}}</div> </div>
排序结果验证
按上述规则排序后的输出顺序完全符合要求:
- Initial - P1 - 2021-12-01 09:20:00
- Ongoing - P2 - 2021-11-01 07:20:00
- Ongoing - coach - 2021-12-01 09:48:00
- InReview - P1 - 2021-11-20 06:55:00
- InReview - P2 - 2021-08-01 09:20:00
- Resolved - P3 - 2021-10-01 05:20:00
内容的提问来源于stack exchange,提问作者Daniel Ellison
相关产品推荐
相关产品推荐

