[英]Sorting a JSON response in Angular by keys
Alright, I've been stuck on this one for a while and can't find an adequate solution out there. 好吧,我已经坚持了一段时间,找不到合适的解决方案。 Basically, I've grouped the posts by date server-side and I want to sort the groups by decending date in Angular. 基本上,我已经按日期在服务器端对帖子进行了分组,并且我想按Angular中的降序对分组进行排序。 I'm assuming a custom filter is the way to go but I haven't been able to get it to work. 我假设要使用自定义过滤器,但我无法使其正常工作。
Here's some of the code: 这是一些代码:
JSON Response: JSON响应:
{"September 20th":[{"id":5,"title":"Test 1","url":"www.google.com","tagline":"Test tagline 1","created_at":"2014-09-20T19:30:44.672Z","updated_at":"2014-09-20T19:30:44.672Z","vote_count":5}],"September 21st":[{"id":6,"title":"Test 2","url":"www.google.com","tagline":"Test tagline 2","created_at":"2014-09-21T00:00:00.000Z","updated_at":"2014-09-20T19:32:41.409Z","vote_count":8}]}
HTML: HTML:
<section ng-controller='MainController'>
<ul ng-repeat="(date, posts) in postList | filter?">
<h1>{{ date }}</h1>
<li ng-repeat='post in posts'>
<p>{{ post.vote_count }}</p>
<button ng-click='upvote(post)' ng-disabled='!currentUser || hasVoted(post.id)'></button>
<a href="{{ post.url }}">{{ post.title }}</a>
</li>
</ul>
</section>
This displays the information perfectly, just in the incorrect order of dates. 这样可以以正确的日期顺序完美地显示信息。
I appreciate any help you can give me! 我感谢您能给我任何帮助!
It's a bit hacky, but it works: 这有点hacky,但是可以用:
Html: HTML:
<section ng-controller='MainController'>
<ul ng-repeat="posts in postList | orderObjectBy:'created_at':true">
<h1>{{ posts.__originalKey }}</h1>
<li ng-repeat='post in posts'>
<p>{{ post.vote_count }}</p>
<button ng-click='upvote(post)' ng-disabled='!currentUser || hasVoted(post.id)'></button>
<a href="{{ post.url }}">{{ post.title }}</a>
</li>
</ul>
</section>
CustomFilter: CustomFilter:
.filter('orderObjectBy', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item, key) {
item.__originalKey=key;
filtered.push(item);
});
filtered.sort(function (a, b) {
return (a[field] > b[field] ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.