好吧,我已经暂时停留在这个问题上并且无法在那里找到适当的解决方案。基本上,我按服务器端的日期对帖子进行了分组,我想通过Angular中的降序日期对组进行排序。我假设自定义过滤器是可行的,但我还没有能够让它工作。
这里有一些代码:
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:
<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>
这将完美地显示信息,只是日期的顺序不正确。
我感谢你能给我的任何帮助!
答案 0 :(得分:0)
有点hacky,但它确实有效:
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:
.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;
};
})