You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>

排序结果验证

按上述规则排序后的输出顺序完全符合要求:

  1. Initial - P1 - 2021-12-01 09:20:00
  2. Ongoing - P2 - 2021-11-01 07:20:00
  3. Ongoing - coach - 2021-12-01 09:48:00
  4. InReview - P1 - 2021-11-20 06:55:00
  5. InReview - P2 - 2021-08-01 09:20:00
  6. Resolved - P3 - 2021-10-01 05:20:00

内容的提问来源于stack exchange,提问作者Daniel Ellison

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:45:04