2

I'm trying to implement server-side pagination on an AngujarJS app but haven't figured out how to get the grand total (not the per-request total) items in a given JSON response without having to do an additional request:

$scope.books = [];
$scope.limit = 3;
$scope.offset = 0;

$scope.search = function () {
    Books.query({ q: $scope.query, limit: $scope.limit, offset: $scope.offset },
        function (response) {
            $scope.books = response;
        }
    );
};

$scope.previous = function () {
    if ($scope.offset >= $scope.limit) {
        $scope.offset = $scope.offset - $scope.limit;
        $scope.search();
    }
}

$scope.next = function () {
    if ($scope.offset <= $scope.limit) {
        $scope.offset = $scope.offset + $scope.limit;
        $scope.search();
    }
}

I've been looking at great contributed directives such as ng-table and ng-grid which already implement this as well as other useful features but I just want to be able to implement this one functionality from scratch to really learn the basics.

Nano Taboada
  • 4,148
  • 11
  • 61
  • 89
  • Add the total number of items in the response returned for each request. – kubuntu Oct 02 '13 at 15:02
  • @ranru: Thanks but I believe there should be a better approach rather than modifying the object collection itself. – Nano Taboada Oct 02 '13 at 15:05
  • If the JSON response contains all the items then you should be able to get that from the length property. However, if each it only contains a subset of the result, I don't think there is any other way than getting the value from the server. – kubuntu Oct 02 '13 at 15:12
  • It's a subset -- that's the purpose of `$scope.limit` – Nano Taboada Oct 02 '13 at 16:15
  • possible duplicate of [how to make a server side pagination with angularjs $resource ?](http://stackoverflow.com/questions/17460003/how-to-make-a-server-side-pagination-with-angularjs-resource) – JBCP Feb 21 '14 at 19:24

1 Answers1

2

Sounds like you are struggling with your api more than angular.

See the answer below for suggestions for the api.

What’s the best RESTful method to return total number of items in an object?

Community
  • 1
  • 1
Chris Tesene
  • 121
  • 6
  • 2
    Django Rest Framework offers a nice paginated result object that offers `total`, along with `next` and `previous` URLs in addition to the paginated result array for example. – Kevin Stone Oct 08 '13 at 07:58