Pexilius Pexilius - 1 year ago 113
AngularJS Question

AngularJS - orderBy vote count

<a ui-sref="detail({id: post._id})" ng-if="post" ng-repeat="post in posts |
orderBy : post.votes.length | limitTo:10" class="list-group-item">
<div class="row">
<div class="col-md-12">
<h5 class="no-margin-top"><span class="glyphicon glyphicon-{{post.type}}-sign"></span> <strong>{{post.birdname}}</strong></h5>
<div class="col-md-4">
<div class="thumbnail no-border no-margin-bottom">
<img ng-src="{{post.picture}}" alt="bird"/>
<div class="col-md-6">
<h5>&#160;<span class="fa fa-map-marker"></span> {{}}</h5>
<h5>&#160;<i class="fa fa-user"></i> {{}}</h5>
<h5>&#160;<i class="fa fa-clock-o"></i> <span am-time-ago="post.created_at"></span></h5>
<hr />

When trying
I get the number of votes (likes) done to that specific post and I'm trying to order them from most amount to least.

In my controller I am simply retrieving all the posts and returning them to the partial:

app.controller('dashboardCtrl', ['$scope', '$http', 'postApi', function($scope, $http, postApi){
$scope.posts = [];
$scope.pageSize = 4;
$scope.currentPage = 1;

.then(function(res) {
$scope.posts = {
return posts;

But the ng-repeat doesnt sort by the highest value. Just to make sure that it is passing along the amount, I did a
right underneath, which does count the amount correctly.

The votes are an array inside the post with an id of all the votes done (linked with a refrence) as shown below:

"_id": "574ddaab594d3e6514ddf6e7",
"created_at": "2016-05-31T18:40:43.727Z",
"author": "Author",
"userId": "154815165165",
"body": "body",
"type": "ok",
"__v": 32,
"votes": [
"comments": []

So as you can see above the post with id
has 2 'likes' aka votes.
Lets take this as an example: if all the other posts had 1 vote, but this one had 2, I would want to show this vote on top.

Answer Source

You just put below filter in your ng-repeat

ng-repeat="post in posts |  orderBy : 'votes.length' : true | limitTo:10"

Instead of

ng-repeat="post in posts | orderBy : post.votes.length | limitTo:10"

Click here to show example in codepen