AngularJS: 先分组再排序
AngularJS: GroupBy then Sort
我有一个集合,我在使用 ng-repeat
在 UI 中显示之前使用 lodash.js groupBy 对其进行分组
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
因此,为了解决您的问题,只需将您的分组对象转换为数组,然后根据需要对其进行排序。
我有一个集合,我在使用 ng-repeat
在 UI 中显示之前使用 lodash.js groupBy 对其进行分组 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
因此,为了解决您的问题,只需将您的分组对象转换为数组,然后根据需要对其进行排序。