javascript - AngularJS:GroupBy 然后排序

标签 javascript angularjs underscore.js lodash

我有一个集合,我使用 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/

相关文章:

angularjs - 在 Angular ngRepeat 内编辑时项目消失

javascript - 为 div 中的所有复选框添加值、文本和状态到数组

jQuery/underscore.js 模板 - 与 IE 6+ 兼容吗?

javascript - jQuery:在文档加载时检查是否选中复选框并执行功能

javascript - 损坏的 JQuery 循环

angularjs - 什么 "things"可以在 Angular.js 中注入(inject)其他人?

javascript - AngularJS:阻止用户访问特定状态

javascript - underscore.js - 确定数组数组中的所有值是否匹配

javascript - 根据表单输入过滤 d3 js 对象

javascript - 如何使用动态 JSON 中的键来创建 javascript 数组?