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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With