我有一个集合,我使用 lodash.js groupBy 对它进行分组,然后使用 ng-repeat 在 UI 中显示
var list = [{id:1,categoryId:1,name:test1},
{id:2,categoryId:2,name:test2},
{id:3,categoryId:12,name:test12}]
vm.myList= _.groupBy(list,function (j) { return j.categoryId; });
console.debug(vm.myList) // this shows the correct ordering!!!
现在,当我使用 ng-repeat 显示它时,它会弄乱顺序
<div ng-repeat="(categoryId, details) in vm.myList| orderBy: 'categoryId'>
{{ categoryId }}
</div>
这显示
1
12
2
如何让它显示
1
2
12
我正在尝试类似的事情,但没有运气
<div ng-repeat="(categoryId, details) in vm.myList| orderBy: 'parseInt(categoryId)'>
{{ categoryId }}
</div>
更新!我发现这在 Angular 1.4.x 中不是问题。不幸的是,我们使用的是旧版本 Angular 1.3.x
最佳答案
首先,orderBy
过滤器仅适用于数组,因此如果您尝试将对象传递给它,将按原样返回传递的对象。
第二个,ngRepeat
You need to be aware that the JavaScript specification does not define the order of keys returned for an object. (To mitigate this in Angular 1.3 the ngRepeat directive used to sort the keys alphabetically.)
Version 1.4 removed the alphabetic sorting.
If this is not desired, the recommended workaround is to convert your object into an array that is sorted into the order that you prefer before providing it to ngRepeat. You could do this with a filter such as toArrayFilter
因此,为了解决您的问题,只需将分组对象转换为数组,然后根据需要对其进行排序。
关于javascript - AngularJS:GroupBy 然后排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31604143/