How to set the sorting order (asc/desc) of an array based on dynamically selected property

↘锁芯ラ 提交于 2020-01-06 14:09:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!