Pexilius Pexilius - 6 months ago 36
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">
{{post.votes.length}}
<div class="col-md-12">
<h5 class="no-margin-top"><span class="glyphicon glyphicon-{{post.type}}-sign"></span> <strong>{{post.birdname}}</strong></h5>
</div>
<div class="col-md-4">
<div class="thumbnail no-border no-margin-bottom">
<img ng-src="{{post.picture}}" alt="bird"/>
</div>
</div>
<div class="col-md-6">
<h5>&#160;<span class="fa fa-map-marker"></span> {{post.place}}</h5>
<h5>&#160;<i class="fa fa-user"></i> {{post.author}}</h5>
<h5>&#160;<i class="fa fa-clock-o"></i> <span am-time-ago="post.created_at"></span></h5>
</div>
</div>
<hr />
</a>


When trying
post.votes.length
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;

postApi.getAllPosts()
.then(function(res) {
$scope.posts = res.data.filter(function(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
{{post.votes.length}}
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": [
"574ede99277c97a810379328",
"574ee07b277c97a81037932a"
],
"comments": []
}


So as you can see above the post with id
574ddaab594d3e6514ddf6e7
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

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

Comments