How to switch order in angular js

I am trying to show data on up and down click on the same button click using angularjs. I can show the data in ascending order. But how do I show the descent on the same button press (as a radio button in jquery). I will tell you about the problem. I have a button in the table header "V" on this click. I have sorted the column in ascending order. We can do descending order on the same button press

when the user first clicks colomn for the first time. The expected result is I can achieve this.

 Calls   Royal Dutch sell

    p        a royal data

    Xgtyu     test royal dat

      

But if he clicks the same button again. Then it will show this Expected result

    Xgtyu     test royal dat

    p        a royal data

   Calls   Royal Dutch sell

      

I need to switch data from upstream to downstream on the same button press.

here is my code http://plnkr.co/edit/cScyd91eHVGTTGN390ez

<div class="row" ng-repeat="column in displayData | orderBy: sortval | filter: query">
        <div class="col col-center brd" ng-repeat="field in column.columns" ng-show="data[$index].checked && data[$index].fieldNameOrPath===field.fieldNameOrPath">{{field.value}}</div>
        <div class="col col-10 text-center brd">
        </div>
      </div>

      

JS code

  $scope.setSort = function(idx){
    $scope.sortval = 'columns['+idx+'].value';
  };

      

+3


source to share


1 answer


Note the syntax for the orderBy filter:

{{ orderBy_expression | orderBy : expression : reverse }}

      

An expression is a column to sort, and the converse can be either true or false. Here is the documentation further explaining this: https://docs.angularjs.org/api/ng/filter/orderBy .

So change your ng repeat to

ng-repeat="column in displayData | orderBy:sortVal:sortDir"

      



Now, in your setSort method, add the following code to control the sort direction:

 if ($scope.sortVal === 'columns['+idx+'].value')
    $scope.sortDir = !$scope.sortDir;

      

Also define the default sort direction at the top of the controller:

$scope.sortDir = false;

      

We initialize it as false as false is asc sort and true is desc sort. Here is the updated plunker: http://plnkr.co/edit/fhcmwqWpv8mt23vV69vZ?p=preview

+10


source







All Articles