Giter Site home page Giter Site logo

angular-paginate-anything's Introduction

Logo

## Angular Directive to Paginate Anything [![Build Status](https://travis-ci.org/begriffs/angular-paginate-anything.png?branch=master)](https://travis-ci.org/begriffs/angular-paginate-anything)

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!

Usage

Include with bower

bower install angular-paginate-anything

Load the javascript and declare your Angular dependency

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 template-url 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

Name Description Access
url url of endpoint which returns a JSON array Read/write. Changing it will reset to the first page.
url-params map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url Read/write. Changing it will reset to the first page.
headers additional headers to send during request Write-only.
page the currently active page Read/write. Writing changes pages. Zero-based.
per-page (default=`50`) Max number of elements per page Read/write. The server may choose to send fewer items though.
per-page-presets Array of suggestions for per-page. Adjusts depending on server limits Read/write.
auto-presets (default=`true`) Overrides per-page presets and client-limit to quantized values 1,2,5,10,25,50... Read/write.
client-limit (default=`250`) Biggest page size the directive will show. Server response may be smaller. Read/write.
link-group-size (default=`3`) Number of elements surrounding current page. illustration Read/write.
num-items Total items reported by server for the collection Read-only.
num-pages num-items / per-page Read-only.
server-limit Maximum results the server will send (Infinity if not yet detected) Read-only.
range-from Position of first item in currently loaded range Read-only.
range-to Position of last item in currently loaded range Read-only.
reload-page If set to true, the current page is reloaded. Write-only.
size Twitter bootstrap sizing `sm`, `md` (default), or `lg` for the navigation elements. Write-only.
passive If using more than one pagination control set this to 'true' on all but the first. Write-only.

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.

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.

Framework Solution
Ruby on Rails begriffs/clean_pagination gem
Node.js node-paginate-anything module
Express JS from scratch howto
ServiceStack for .NET .NET howto

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 /items HTTP/1.1
Range-Unit: items
Range: 0-24

Response

HTTP/1.1 206 Partial Content
Accept-Ranges: items
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 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.

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.

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.

angular-paginate-anything's People

Contributors

begriffs avatar dnauck avatar gvn avatar lucnap avatar mekosan avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.