0

I have table headers like the following that set the orderByField and reverseSort variable:

       <th class='header'> 
<a href="" ng-click="orderByField='success'; reverseSort = !reverseSort">
Successes <span ng-show="orderByField == 'success'"><span ng-show="!reverseSort"
class="glyphicon glyphicon-chevron-up"></span><span ng-show="reverseSort" class="glyphicon glyphicon-chevron-down"></span></span>
     </a>
  </th>

I have an ng-repeat:

 <tbody>
    <tr ng-repeat="item in items| filter:paginate |orderBy:sorter:reverseSort">
         <td>{{item.name}}</td>
        <td>{{item.failPercentage}}</td>
       <td>{{item.failure}}</td>
      <td>{{item.success}}</td>
  </tr>
</tbody>

I use the ui.bootstrap library for this as well:

            <uib-pagination total-items="totalItems"
                            ng-model="currentPage"
                            max-size="15" boundary-links="true"
                            items-per-page="numPerPage" class="pagination-sm">
            </uib-pagination>

In my controller I have a paginate function and sorter function that are applied to my ng-repeat

    $scope.paginate = function (value) {
    var begin, end, index;
    begin = ($scope.currentPage - 1) * $scope.numPerPage;
    end = begin + $scope.numPerPage;
    index = $scope.items.indexOf(value);
    return (begin <= index && index < end);
};
$scope.sorter = function (item) {
        return item[$scope.orderByField];
};

my sort just uses the default sort, but when i do sort, it sorts each page independent of each other. how do i apply the sort to all pages dependent of one another (and then send the user to the first page of pagination)?

Community
  • 1
  • 1
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78

1 Answers1

1

You do it in wrong order - first you need to sort, then paginate.

item in items| orderBy:sorter:reverseSort | filter:paginate

Also notice that your paginate function is doing exactly what Array.slice does, so better make your own filter:

app.filter('slice', function() {
  return function(arr, pageSize, pageNum) {
    ...
    return arr.slice(begin, end);
  };
});

item in items| orderBy:sorter:reverseSort | slice:numPerPage:currentPage 

Going deeper: using filters on large arrays is bad practice, since whenever any scope variable changes this filters will launch. If you have array of i.e. 10k elements that may hurt. So better sort manually in ng-click on th.

Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38