npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

angular-paginate-anything

v4.2.0

Published

Add server-side pagination to any list

Downloads

2,909

Readme

Add server-side pagination to any list or table on the page. This directive connects a variable of your choice on the local scope with data provied on a given URL. It provides a pagination user interface that triggers updates to the variable through paginated AJAX requests.

Pagination is a distinct concern and should be handled separately from other app logic. Do it right, do it in one place. Paginate anything!

DEMO

Usage

Include with bower

bower install angular-paginate-anything

The bower package contains files in the dist/directory with the following names:

  • angular-paginate-anything.js
  • angular-paginate-anything.min.js
  • angular-paginate-anything-tpls.js
  • angular-paginate-anything-tpls.min.js

Files with the min suffix are minified versions to be used in production. The files with -tpls in their name have the directive template bundled. If you don't need the default template use the angular-paginate-anything.min.js file and provide your own template with the templateUrl attribute.

Load the javascript and declare your Angular dependency

<script src="bower_components/angular-paginate-anything/dist/angular-paginate-anything-tpls.min.js"></script>
angular.module('myModule', ['bgf.paginateAnything']);

Then in your view

<!-- elements such as an ng-table reading from someVariable -->

<bgf-pagination
  collection="someVariable"
  url="'http://api.server.com/stuff'">
</bgf-pagination>

The pagination directive uses an external template stored in tpl/paginate-anything.html. Host it in a place accessible to your page and set the templateUrl attribute. Note that the url param can be a scope variable as well as a hard-coded string.

Benefits

  • Attaches to anything — ng-repeat, ng-grid, ngTable etc
  • Server side pagination scales to large data
  • Works with any MIME type through RFC2616 Range headers
  • Handles finite or infinite lists
  • Negotiates per-page limits with server
  • Keeps items in view when changing page size
  • Twitter Bootstrap compatible markup

Directive Attributes

Events

The directive emits events as pages begin loading (pagination:loadStart) or finish (pagination:loadPage) or errors occur (pagination:error). To catch these events do the following:

$scope.$on('pagination:loadPage', function (event, status, config) {
  // config contains parameters of the page request
  console.log(config.url);
  // status is the HTTP status of the result
  console.log(status);
});

The pagination:loadStart is passed the client request rather than the server response.

To trigger a reload the pagination:reload event can be send:

function () {
  $scope.$broadcast('pagination:reload');
}

How to deal with sorting, filtering and facets?

Your server is responsible for interpreting URLs to provide these features. You can connect the url attribute of this directive to a scope variable and adjust the variable with query params and whatever else your server recognizes. Or you can use the url-params attribute to connect a map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. Changing the url or url-params causes the pagination to reset to the first page and maintain page size.

Example:

$scope.url = 'api/resources';
$scope.urlParams = {
  key1: "value1",
  key2: "value2"
};

Will turn into the URL of the resource that is being requested: api/resources?key1=value1&key2=value2

What your server needs to do

This directive decorates AJAX requests to your server with some simple, standard headers. You read these headers to determine the limit and offset of the requested data. Your need to set response headers to indicate the range returned and the total number of items in the collection.

You can write the logic yourself, or use one of the following server side libraries.

For a reference of a properly configured server, visit pagination.begriffs.com.

Here is an example HTTP transaction that requests the first twenty-five items and a response that provides them and says there are one hundred total items.

Request

GET /stuff HTTP/1.1
Range-Unit: items
Range: 0-24

Response

HTTP/1.1 206 Partial Content
Content-Range: 0-24/100
Range-Unit: items
Content-Type: application/json

[ etc, etc, ... ]

In short your server parses the Range header to find the zero-based start and end item. It includes a Content-Range header in the response disclosing the unit and range it chooses to return, along with the total items after a slash, where total items can be "*" meaning unknown or infinite.

When there are zero elements to return your server should send status code 204 (no content), Content-Range: */0, and an empty body (or [] if the endpoint normally returns a JSON array).

To do all this header stuff you'll need to enable CORS on your server. In a Rails app you can do this by adding the following to config/application.rb:

config.middleware.use Rack::Cors do
  allow do
    origins '*'
    resource '*',
      :headers => :any,
      :methods => [:get, :options],
      :expose => ['Content-Range', 'Accept-Ranges']
  end
end

For a more complete implementation including other appropriate responses see my clean_pagination gem.

Using the load-fn callback

Instead of having paginate-anything handle the http requests there is the option of using a callback function to perform the requests. This might be helpful e.g. if the data does not come from http endpoints, further processing of the request needs to be done prior to submitting the request or further processing of the response is necessary.

The callback can be used as follows:

<bgf-pagination collection="data" page="filter.page" per-page="filter.perpage" load-fn="callback(config)"></bgf-pagination>
$scope.callback = function (config) {
  return $http(config);
}

// alternatively
$scope.callback = function(config) {
  return $q(function(resolve) {
    resolve({
      data: ['a', 'b'],
      status: 200,
      config: {},
      headers: function(headerName) {
        // fake Content-Range headers
        return '0-1/*';
      }
    });
  });
}

Further reading

Thanks

Thanks to Steve Klabnik for discussions about doing hypermedia/HATEOAS right, and to Rebecca Wright for reviewing and improving my original user interface ideas for the paginator.