在 ng-repeat 中引用 orderBy 中的外部范围变量

Referring to outer scope variables in orderBy inside ng-repeat

我想要一个在某些外部查找中按值排序的 ng-repeat table。

例如,假设我有一个 items 的列表,每个项目都有一个 itemType。我在范围内有一个单独的 itemTypePriorities 查找 table,这样 itemTypePriorities[someItemType] 给出给定项目类型的优先级。现在,我想按优先顺序显示项目。我正在尝试以下操作:

<div ng-repeat="item in items | orderBy:'itemTypePriorities[item.itemType]'>

但它似乎不起作用 - 我的猜测是它在 item 的上下文中解释 orderBy 表达式,即它试图通过无意义的表达式 item.itemTypePriorities[item.itemType].[= 进行排序19=]

有没有办法重写 ng-repeat 使其正确工作,无需修改任何 itemsitemTypePriorities 数组方式?

您当然可以使用 orderBy 过滤器,但我认为您需要创建一个自定义函数来对其进行排序。

例如:

<div ng-repeat="item in items | orderBy:myFunction>

其中 myFunction 在控制器中的某处声明为:

$scope.myFunction = function(el){
    //el is the current element under evaluation
}

并且应该 return 一个将与 <、=== 和 > 与另一个进行比较的值。在您的情况下,函数可以是:

$scope.myFunction = function(el){
    return itemTypePriorities.indexOf(el);
}

这应该有效