gpt4 book ai didi

javascript - ngRepeat - 首先按特定键对对象进行排序

转载 作者:行者123 更新时间:2023-12-03 04:39:43 29 4
gpt4 key购买 nike

我正在编写一个 AngularJS 应用程序(Angular 1),它需要在页面上显示一个表格列表。然而,某些键需要首先显示,如下所示:

<div>baz (data)</div>
<div>bar (data)</div>
<div>foo (data)</div>
<div>baa (data)</div>

我发现我需要使用 orderBy filter ,但是我似乎无法让它发挥作用。有谁知道我怎样才能实现这一目标?

JS:

angular.module("MyModule").controller("Test", function() {

this.sort = ["baz", "bar"];

this.data = {
"foo": { /* snip */ },
"bar": { /* snip */ },
"baz": { /* snip */ },
"baa": { /* snip */ }
};

});

HTML:

<div ng-controller="Test as T">
<div ng-repeat="(title, row) in T.data"> <!-- Not sure how I would go about sorting these keys by certain ones first -->
{{ title }} ({{ row }})
</div>
</div>

最佳答案

您需要使用 orderBy ,遗憾的是它不适用于对象,因此您必须编写自定义 toArray 过滤器。

angular.module("MyModule").controller("Test", function() {

this.data = {
"foo": { /* snip */ },
"bar": { /* snip */ },
"baz": { /* snip */ },
"baa": { /* snip */ }
};

this.customSort = function(a, b){
/* Whatever way you need to do this */
var sort = ["baz", "bar"];
return sort.indexOf(a) < sort.indexOf(b) ? 1 : -1;
}

}).filter('toArray', function () {

return function (obj) {
if (!(obj instanceof Object)) {
return obj;
}

return Object.keys(obj).map(function (key) {
return Object.defineProperty(obj[key], '$key', {__proto__: null, value: key});
});
}
});

HTML

<div ng-controller="Test as T">
<div ng-repeat="item in T.data | toArray | orderBy: $key : false : T.customSort">
{{ item.$key }} ({{ item.value }})
</div>
</div>

Angular orderBy docsDiscussion on orderBy for objects

关于javascript - ngRepeat - 首先按特定键对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43137968/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com