问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/28917819/how-to-set-the-sorting-order-asc-desc-of-an-array-based-on-dynamically-selecte