Search code examples
angularjssortingangularjs-orderby

AngularJS: Sorting issue


Making use of AngularJS orderBy filter I've created a sortable table here,

http://plnkr.co/edit/AarOSuawXVYe9C5LBDOK?p=preview

I am using the value of 'reverse' for each table header on click to determine the direction of the sort. This creates an obvious problem however as I click on different table headers they simply go to the opposite of the reverse value which may have previously been changed from another table header.

<th ng-click="predicate = 'character'; reverse=!reverse">alpha</th>
<th ng-click="predicate = 'num'; reverse=!reverse">num</th>
<th ng-click="predicate = 'dec'; reverse=!reverse">dec</th>
<th ng-click="predicate = 'value'; reverse=!reverse"></th>
<th ng-click="predicate = 'date'; reverse=!reverse">date</th>

and the ng-repeat populating my table rows using the orderBy filter

<tr ng-repeat="line in infoCtrl.data | orderBy:predicate:reverse">

How can I isolate the scope of reverse, or give them an individual reverse value each?


Solution

  • Ideally, I would check the current value of predicate before reversing the sort boolean. If it's same, reverse it. Otherwise, reset it to the default.

    Have a function in your controller for sorting:

     $scope.predicate = "character";
     $scope.reverse = false    
     $scope.sort = function(p) {
         if ($scope.predicate == p) {
             $scope.reverse = !$scope.reverse;
         } else {
             $scope.predicate = p;  
             $scope.reverse = false;
         }
     }
    

    and call this function from html:

        <th ng-click="sort('character')">alpha</th>
        <th ng-click="sort('num')">num</th>
        <th ng-click="sort('dec')">dec</th>
        <th ng-click="sort('value')"></th>
        <th ng-click="sort('date')">date</th>