如何设置阵列基于动态选择属性的排序顺序(ASC / DESC) [英] How to set the sorting order (asc/desc) of an array based on dynamically selected property
问题描述
我电影的一个数组
以下结构的对象:
$scope.movies = [
{title: "some title", rank: 13, imdbRating: 828},
// ...
];
和我想的财产标题
,等级
或 imdbRating对它们进行排序
- 选择具有<选择>
,并通过ASC /递减排序 - 用按钮选择。这是我做的,但是,排序似乎得到复位。
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]">
我想要做的是选择一个选项,选择排序属性 orderProp
,如果用户点击ASC或降序按钮重新排序列表。
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.
不过,订货不知道我选哪些类别通过,因此它不能做的ASC或DESC正确。选项被删除,以及视觉,如果我点击递增/递减按钮。
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?
推荐答案
的排序依据
过滤器接受两个参数:1)的财产,和2)顺序:
The orderBy
filter accepts two parameters: 1) the property, and 2) the order:
<div ng-repeat="item in items | orderBy:prop:isReverse">
所以,你的情况,你需要设置 isReverse
在 NG-点击
A的ASC /说明按钮相应。您已经正确地设置属性&LT;选择方式&gt;
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 - 为了说明
这篇关于如何设置阵列基于动态选择属性的排序顺序(ASC / DESC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!