AngularJS Paging orderBy only affects displayed page

All we need is an easy explanation of the problem, so here it is.

Can anyone point me in the right direction to figure out a way to fix the way paging and orderBy work together in Angular?

Currently, I can orderBy and page the results of the data[], but the orderBy filter only affects the each page individually.

For example, if I sort in reverse order by ID, page 1 will list 10-1, and page 2 will list 15-11, as opposed to starting with 15 and going to 1 by the end of the second page.

I have a basic fiddle here http://jsfiddle.net/ZbMsR/

Here is my controller:

function MyCtrl($scope) {
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.orderBy = "-appId";
    $scope.data = [
        {'appId': 1}, {'appId': 2}, {'appId': 3}, {'appId': 4}, {'appId': 5}, {'appId': 6}, {'appId': 7}, {'appId': 8}, {'appId': 9},{'appId': 10}, {'appId': 11}, {'appId': 12}, {'appId': 13}, {'appId': 14}, {'appId': 15}
];

    $scope.numberOfPages=function(){
        return Math.ceil($scope.data.length/$scope.pageSize);                
    };
}

//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});

Here is the relevant portion of my View

 <strong>Sort By:</strong> <a ng-click="orderBy = 'appId'; reverse=!reverse">Newest</a>
 <ul>
    <li ng-repeat="item in data | startFrom:currentPage*pageSize | limitTo:pageSize | orderBy:orderBy:reverse">
        {{item.appId}}
    </li>
 </ul>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If you have complete client-side paging, then you can just change order of filters:

<li ng-repeat="item in data | orderBy:orderBy:reverse | startFrom:currentPage*pageSize | limitTo:pageSize ">

Is that what you expected?

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply