I am writing a web app that allows users to post to a server and the front end displays all the posts. However, when a user adds a post, it goes to the bottom of all posts first. I want the newest post to go to the top of all posts instead.
I tried using:
ng-repeat="post in posts | orderBy:'-'"
and
ng-repeat="post in posts | orderBy:'-index'"
This is my code for the table:
<div ng-repeat="post in posts | orderBy:'-'">
<table>
<tr>
<td>{{$index}}</td>
<td>{{post.username}}</td>
<td>{{post.title}}</td>
<td>{{post.content}}</td>
<td>{{post.comment}}</td>
</tr>
</table>
</div>
However these two approaches do not work. Is there another way?
You can order them according to their position in the unsorted posts
array. You can do this with a function like so:
$scope.newestFirst = function(post) {
return -$scope.posts.indexOf(post);
}
And then in the HTML: <div ng-repeat="post in posts | orderBy:newestFirst">
Here's a fiddle. With the newestFirst
sort, new posts get added to the top of the list.
You'll notice that even as you change the order of the posts, the index column stays the same. It seems that $index
gives the index of each post in its current sort. Ordering by $index
still appears to sort the posts by their index in the source array, but ordering by a string of gibberish produces the same result, so I think this is coincidental.