如何根据动态选择的属性设置数组的排序顺序(asc/desc) [英] How to set the sorting order (asc/desc) of an array based on dynamically selected property
问题描述
我有一个具有以下结构的 movie
对象数组:
$scope.movies = [{title: "some title", rank: 13, imdbRating: 828},//...];
我想按属性title
、rank
或imdbRating
对它们进行排序 - 用,并按 asc/desc 排序 - 用按钮选择.这就是我所做的,但是,顺序似乎被重置了.
我想要做的是选择一个选项来选择排序属性 orderProp
以及如果用户单击asc"或desc"按钮来重新排序列表.
但是,排序不知道我按什么类别排序,因此无法正确执行 asc 或 desc.如果我单击 asc/desc 按钮,选项也会在视觉上被删除.
有什么好的解决办法吗?
orderBy
过滤器接受两个参数:1) 属性,2) 顺序:
因此,在您的情况下,您需要相应地在Asc"/Desc"按钮的 ng-click
中设置 isReverse
.您已经使用
正确设置了属性.
在控制器中设置这些的初始值也是一个好主意:
$scope.isReverse = false;//升序$scope.orderProp = "title";
plunker - 用于说明
I have an an array of movie
objects of the following structure:
$scope.movies = [
{title: "some title", rank: 13, imdbRating: 828},
// ...
];
and I would like to sort them by the property title
, rank
or imdbRating
- selected with <select>
, and by asc/desc ordering - selected with buttons. This is what I did, however, the ordering seems to get reset.
<select ng-model="orderProp" id="input">
<option value="title">Alphabetical</option>
<option value="rank">Rank</option>
<option value="imdbRating">Rating</option>
</select>
<button ng-click="orderProp='+'-orderProp;orderProp='-'-orderProp; orderProp='+'+orderProp " >Asc
</button>
<button ng-click="orderProp='+'-orderProp;orderProp='-'-orderProp;orderProp='-'+orderProp" >Desc
</button>
<li ng-repeat="movie in movies | filter:search:strict | orderBy [orderProp]">
What I want to do is to choose an option to select the sorting property orderProp
and if user clicks "asc" or "desc" buttons to re-order the list.
However, ordering does not know what categories I am sorting by so it can not do asc or desc correctly. Option get deleted as well visually if i click the asc / desc buttons.
Is there good solution to this?
解决方案 The orderBy
filter accepts two parameters: 1) the property, and 2) the order:
<div ng-repeat="item in items | orderBy:prop:isReverse">
So, in your case, you need to set the isReverse
in the ng-click
of a "Asc"/"Desc" buttons accordingly. You are already setting the property correctly with <select>
.
<select ng-model="orderProp">
<!-- as you do now -->
</select>
<button ng-click="isReverse = false">Asc</button>
<button ng-click="isReverse = true">Desc</button>
<li ng-repeat="movie in movies | orderBy: orderProp : isReverse">
It's also a good idea to set the initial value of these in the controller:
$scope.isReverse = false; // for ascending order
$scope.orderProp = "title";
plunker - for illustration
这篇关于如何根据动态选择的属性设置数组的排序顺序(asc/desc)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文