AngularJS Paging orderBy only affects displayed page
Asked Answered
W

1

11

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>
Waterway answered 7/1, 2013 at 15:24 Comment(0)
D
39

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?

Dichroscope answered 7/1, 2013 at 15:39 Comment(2)
beautiful! Was about to hunker down to wrote a ton of code. Phew!Geiss
@Anamadeya; It most likely works in the order it encounters each individual command. So it limits by pageSize, then it orders by the ordering function. By reversing them, it orders by the ordering function, THEN it limits to the pageSize.Arrington

© 2022 - 2024 — McMap. All rights reserved.