简体   繁体   中英

Limit and Offset data results in AngularJS for Pagination

Does AngularJS have Limit and Offset request methods when calling an external data resource that supports them?

I imagine there is a more elegant solution than this, where I am passing the limit and offset via the routeParams:

function ListCtrl($scope, $http, $routeParams) {
$http.jsonp('http://www.example.com/api/list.jsonp?callback=JSON_CALLBACK&limit=' + $routeParams.limit + '&offset=' + $routeParams.offset,{callback: 'JSON_CALLBACK'}).success(function(data) {
$scope.list = data;
  });
}

A complete pagination solution is: (1) a service that communicates with the server/database, (2) a directive to handle next/prev, and (3) a controller to glue it together.

Once you have the directive and the service, your controller is as simple as this:

app.controller('MainCtrl', function($scope, myData) {
  $scope.numPerPage = 5;
  $scope.noOfPages = Math.ceil(myData.count() / $scope.numPerPage);
  $scope.currentPage = 1;

  $scope.setPage = function () {
    $scope.data = myData.get( ($scope.currentPage - 1) * $scope.numPerPage, $scope.numPerPage );
  };

  $scope.$watch( 'currentPage', $scope.setPage );
});

With equally simple HTML:

<body ng-controller="MainCtrl">
  <ul>
    <li ng-repeat="item in data">{{item.name}}</li>
  </ul>
  <pagination num-pages="noOfPages" current-page="currentPage" class="pagination-small"></pagination>
</body>

Here's a complete Plunker: http://plnkr.co/edit/Mg0USx?p=preview . It uses the pagination directive of ui-bootstrap , which is a work in progress.

AngularJs is clientside. It is the external data resource's provider who should support those parameters.

A possible solution for your problem could be $resource (or the params option Mark mentioned ):

var UserAccounts = $resource('/useraccounts/:userId/limit/:limit/offset:offset', {userId:'@id'});
var accounts = User.get({userId:123, limit:10, offset:10}, function() {
});

Of course, server side will need to read the parameters differently.

I'm not sure I understand your question, but $http methods have a config parameter which is an object, one property of which is the "params" object:

params – {Object.} – Map of strings or objects which will be turned to
?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.

If your "limit" and "offset" values are in $routParams, then that seems like a fine place to get them from. However, you may want to consider wrapping the code that interfaces with your server into an Angular service. This service could store the current limit and offset values. You can inject the service into your controllers to get access to the functions (and/or data) that the service provides.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM