【问题标题】:AngularJS sorting by attribute and custom filterAngularJS按属性和自定义过滤器排序
【发布时间】:2017-10-06 14:22:14
【问题描述】:

我看到很多答案和文档表明您可以将一组属性名称传递给 Angular 的 orderBy 过滤器以按多个字段排序。但是,我的对象属性之一是存储为文本的数字(字段可以是“100”、“75”、“50”或“

<div ng-repeat="item in items | orderBy:sortFunction">
   {{item.itemStatus}} - {{item.itemLevel}}
</div>

//Function in controller...
$scope.sortFunction = function(item) {
   return parseInt(item.itemLevel);
}

我现在要做的是首先按 item.itemStatus 排序,然后按 item.itemLevel 作为数字排序。有没有办法在不首先更改我的数据模型的情况下做到这一点?我可以遍历所有项目并添加一个新属性,即 itemLevel 作为数字,然后使用过滤

 ng-repeat="item in items | orderBy:['itemStatus','itemLevelAsNumber']

但我想知道是否有更好的方法。我试过了

 ng-repeat="item in items | orderBy:['itemStatus',sortFunction]

但我认为在这种情况下使用函数需要将属性名称作为字符串返回。

谢谢!

【问题讨论】:

  • 我没有进行二次排序的答案,但我确实想指出自定义比较器函数需要两个参数,因为该函数需要在集合的两个元素之间进行比较。然后,如果两个项目相等,则必须返回 0,如果第一个值小于第二个值,则返回 -1,如果第一个值大于第二个值,则返回 1。 docs.angularjs.org/api/ng/filter/orderBy
  • 但我认为在该场景中使用函数需要将属性名称作为字符串返回。不,它的工作方式与您的第一个示例相同。@987654323 @ 所以item in items | orderBy:['itemStatus',sortFunction] 应该没问题。证明了fiddle
  • @George - 你是对的。我的问题是 parseInt("

标签: javascript angularjs sorting


【解决方案1】:

问题出在我的 sortFunction 上。我没有意识到 parseInt 只会在数字是第一个的情况下从混合值中提取数字。

 parseInt("25") === 25; //true
 parseInt("25+") === 25; //true
 parseInt("<25") === 25; //false - actually returns NaN

我将 sortFunction 更新为

 return parseInt(item.itemLevel.replace('<',''));

而视图中的多级orderBy就是我认为现在应该的样子:

 ng-repeat="item in items | orderBy:['itemStatus',sortFunction]

感谢cmets!

【讨论】:

  • 我建议您使用 Regex 进行替换,因为如果您使用它,将来它会更加强大。很高兴您解决了您的问题,并感谢您在此处发布答案,而不是只为自己保密!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 2015-07-26
  • 2013-11-29
  • 1970-01-01
相关资源
最近更新 更多