Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangularjs-ng-repeat

how to toggle orderby in angular js


I am trying to show data in ascending and descending on same button click using angularjs .I am able to show data in ascending order .But how I will show descending on same button click (as a toggle in jquery ). I will tell you problem I have button on my table header "V" on that click I sorted column in ascending order .can we do descending order on same button click

when user click first time on colomn first ..Expected result is this I am able to achieve this .

 Calls   Royal Dutch sell

    p        a royal data

    Xgtyu     test royal dat

But if he again click on same button .Then it will show this Expected result

    Xgtyu     test royal dat

    p        a royal data

   Calls   Royal Dutch sell

I need to toggle data from ascending to descending on same button click .

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';
  };

Solution

  • Notice the syntax of the orderBy filter:

    {{ orderBy_expression | orderBy : expression : reverse }}
    

    Expression is the column to sort by, and reverse 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 manage 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 to false, since false is asc sort, and true is desc sort. Here is an updated plunker: http://plnkr.co/edit/fhcmwqWpv8mt23vV69vZ?p=preview