AngularJS:用于反转 table 行顺序的 orderBy 过滤器不起作用
AngularJS: orderBy filter to reverse the order of the table rows does not work
我正在编写一个 Web 应用程序,允许用户 post 到服务器,前端显示所有 post。但是,当用户添加 post 时,它会先到达所有 post 的底部。我希望最新的 post 转至所有 post 的顶部。
我尝试使用:
ng-repeat="post in posts | orderBy:'-'"
和
ng-repeat="post in posts | orderBy:'-index'"
这是我的代码 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>
然而这两种方法都行不通。还有别的办法吗?
您可以根据它们在未排序的 posts
数组中的位置对它们进行排序。您可以使用如下函数执行此操作:
$scope.newestFirst = function(post) {
return -$scope.posts.indexOf(post);
}
然后在HTML中:<div ng-repeat="post in posts | orderBy:newestFirst">
这是 fiddle。使用 newestFirst
排序,新的 post 被添加到列表的顶部。
您会注意到,即使您更改 post 的顺序,索引列也保持不变。似乎 $index
在其 current 排序中给出了每个 post 的索引。按 $index
排序似乎仍然按源数组中的索引对 post 进行排序,但按乱码字符串排序会产生相同的结果,所以我认为这是巧合。
我正在编写一个 Web 应用程序,允许用户 post 到服务器,前端显示所有 post。但是,当用户添加 post 时,它会先到达所有 post 的底部。我希望最新的 post 转至所有 post 的顶部。
我尝试使用:
ng-repeat="post in posts | orderBy:'-'"
和
ng-repeat="post in posts | orderBy:'-index'"
这是我的代码 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>
然而这两种方法都行不通。还有别的办法吗?
您可以根据它们在未排序的 posts
数组中的位置对它们进行排序。您可以使用如下函数执行此操作:
$scope.newestFirst = function(post) {
return -$scope.posts.indexOf(post);
}
然后在HTML中:<div ng-repeat="post in posts | orderBy:newestFirst">
这是 fiddle。使用 newestFirst
排序,新的 post 被添加到列表的顶部。
您会注意到,即使您更改 post 的顺序,索引列也保持不变。似乎 $index
在其 current 排序中给出了每个 post 的索引。按 $index
排序似乎仍然按源数组中的索引对 post 进行排序,但按乱码字符串排序会产生相同的结果,所以我认为这是巧合。