如何订购帖子自上而下的结构(最高likes
号的帖子将是第一个,最后一个是最低likes
个号码的帖子。要做到这一点,我设置oderBy:likes.length
但它不起作用。请帮忙,谢谢!
function MyController($scope) {
$scope.posts = [{"title": "AAtitle",
"content":"AAcontent",
"likes":["person1", "person2", "person3"]
},
{"title": "BBtitle",
"content":"BBcontent",
"likes":["person10"]
},
{"title": "CCtitle",
"content":"CCcontent",
"likes":["person10","person11", "person100", "person1", "person2"]
}
]
}
<div ng-controller = "MyController">
<ul>
<li ng-repeat = "post in posts | oderBy: likes.length">
<div> {{post.title}} </div>
<div> {{post.content}} </div>
<div> {{post.likes.length}} </div>
</li>
</ul>
</div>
答案 0 :(得分:1)
在视图中显示之前,您可以编写一个函数在控制器中进行排序。或者更可取的是,您可以编写自定义过滤器
过滤器:
angular.module('YourAppName', [])
.filter('orderByLikes', function() {
function compare(a, b) {
return b.likes.length - a.likes.length;
}
return function (input) {
return input.sort(compare);
}
});
查看:
<div ng-controller = "MyController">
<ul>
<li ng-repeat = "post in posts | orderByLikes:posts">
<div> {{post.title}} </div>
<div> {{post.content}} </div>
<div> {{post.likes.length}} </div>
</li>
</ul>
</div>
这是一个有效的Fiddle