• Stars
    star
    517
  • Rank 85,558 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

À la carte server-side pagination

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!

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

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.
transform-response Function that will get called once the http response has returned. See Angular's $https documentation for more information. Read/write. Changing it will reset to the first page.
method Type of request method. Can be either GET or POST. Default is GET. Read/write.
post-data An array of data to be sent when method is set to POST. Read/write.
load-fn A callback function to perform the request. Gets the http config as parameter and must return a promise. 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.

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.

Framework Solution
Ruby on Rails begriffs/clean_pagination gem
Node.js node-paginate-anything module
Express JS from scratch howto
ServiceStack for .NET Service Stack .NET howto
ASP.NET Web API ASP.NET Web API 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 /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.

More Repositories

1

css-ratiocinator

because your CSS is garbage
JavaScript
1,027
star
2

haskell-vim-now

One-line Haskell Vim install
Shell
987
star
3

lucre

Let people pay you for any or no reason.
Ruby
506
star
4

heroku-buildpack-ghc

Deploy Haskell apps to Heroku
Shell
272
star
5

pg_rational

Precise fractional arithmetic for PostgreSQL
PLpgSQL
229
star
6

objgrep

Find strings inside complicated javascript objects
JavaScript
160
star
7

immutube

Youtube + functors, a most unlikely combo
JavaScript
141
star
8

pg_listen

Trigger shell command from NOTIFY
C
83
star
9

gitftp

Browse git over anonymous FTP
C
82
star
10

mimedown

markdown to multipart mime
C
79
star
11

c-mix

Demo of C project with Haskell functions
C
77
star
12

microservice-template

Basic architecture for running and monitoring workers
Shell
70
star
13

postgrest-example

Migrations for an example conference API
PLpgSQL
70
star
14

styleguide_rails

generate a living styleguide with one command
JavaScript
69
star
15

libderp

C collections. Easy to build, boring algorithms. Dumb is good.
C
45
star
16

haskell-pair

Haskell pair programming server via Vagrant
Shell
41
star
17

react-showpiece

Eminently styleable markup
CSS
37
star
18

obsd

Redacted config files
Vim Script
36
star
19

clean_pagination

API pagination the way RFC7233 intended it
Ruby
33
star
20

vimrc

An old plugin-heavy vim config (I do things differently nowadays)
Vim Script
31
star
21

algorithm-freezer

Know your algorithms cold!
Haskell
29
star
22

utofu

Unicode Trust on First Use (TOFU)
C
28
star
23

haskell-circle-example

Exemplary Stack-based template for Circle CI
Haskell
16
star
24

groupthink

obey the masses with realtime voting
JavaScript
15
star
25

autolytics

An embarrassment of analytics riches
12
star
26

wc

Beating haskell with C
C
11
star
27

haskell-postgres-examples

A cookbook for Postgres in Haskell
Haskell
10
star
28

picobounce

Experiment to build an IRC bouncer out of independent programs connected by named pipes. Only half done.
C
8
star
29

mother-structures

Programming via abstract math
CoffeeScript
8
star
30

randln

Fast, flexible, portable way to get random lines out of files
C
6
star
31

lexyacc

Learning to parse
Lex
6
star
32

dumbus

🚌 Hyperefficient bus planning for dumbphones
Haskell
6
star
33

aeson-t

Transform JSON
Haskell
6
star
34

libc

Implementing the C standard library
C
5
star
35

posix-man

Man pages for POSIX (sections 0,1,3; issues 6 and 7)
Roff
5
star
36

clache

Run Lazy K programs in the cloud
Ruby
5
star
37

aws_pipes

AWS queues à la Unix
Ruby
5
star
38

libscorm

Create SCORM 2004 courses in Flash or HTML
JavaScript
5
star
39

findrss

Search (un)common paths to find the Atom or RSS feed of a site
Shell
5
star
40

lancelot

Your knight in shining ASCII armor
Haskell
4
star
41

sinatra-sql

Easy PostgreSQL access with migrations in Sinatra
Ruby
4
star
42

generator-omni-module

Write JS modules that run everywhere
JavaScript
4
star
43

micro-scraper

Microservice to download pages
Haskell
4
star
44

wchar-conformance

Test ISO 10646 conformance of wchar_t
C
4
star
45

ordinary

Transfinite arithmetic in Ruby
Ruby
4
star
46

kr

Quick 'n dirty K&R exercises
C
3
star
47

incl

Preprocessor to include files into output stream
C
3
star
48

philosoraptor

Logic programming in JavaScript
3
star
49

qwertywords

Words that are fun to type like figment ajangle
C
3
star
50

jsobject

Nicer JavaScript objects through ExternalInterface in ActionScript 3
ActionScript
3
star
51

itertools

Python itertools for Ruby
Ruby
3
star
52

turing

There are many like it, but this one is mine
C
2
star
53

float

Experiments in number representations, a collaboration with Eric Bavier
C
2
star
54

endoxa-graph

everything's connected, man
JavaScript
2
star
55

doublekill

Weird experiments with signals
C
2
star
56

twittective

Some screen scraping in Haskell
Haskell
2
star
57

quickcheck-simple

Project template for doing Haskell exercises
Haskell
2
star
58

angular-http-batch

Leap multiple $http requests in a single bound
JavaScript
2
star
59

retags

Keep ctags up to date with minimal overhead
Shell
2
star
60

pthread-test

Exercises from Butenhof's book
C
2
star
61

semln

Filter to add semantic line breaks in many languages
C
2
star
62

hasql-stress

Trying to reproduce deadlock
Haskell
2
star
63

git-zophrenic

Finds the secret government messages in your Git hashes
Shell
1
star
64

stalk27

When will route 27 actually arrive? No more lies.
Shell
1
star
65

jvscrpt

Drop the function arguments and write less code
JavaScript
1
star
66

multiparse

Drafts for my parsing article
Yacc
1
star
67

ringfifo

Nonblocking multi-use named pipes
C
1
star
68

begriffs.com

my site
CSS
1
star
69

CopernicusJS

A revolution in CSS positioning
JavaScript
1
star
70

angular-patience

Efficiently wait for long server processing
JavaScript
1
star
71

flexicode

Tools scanning Unicode in Flex
C
1
star
72

stm32f411

STM32F4 (STM32F411CEU6) "black pill" development with non-proprietary tools
C
1
star
73

scheme48hrs

Write yourself a Scheme in 48 hours exercises
Haskell
1
star
74

getclojure-ui

A front-end for devn/getclojure
Ruby
1
star
75

apue

Advanced Programming in the UNIX Environment
C
1
star
76

1up

Project page for my one-year challenge
Ruby
1
star
77

warp-async-test

Can warp handle multiple requests at once?
Haskell
1
star
78

rustybank

Concurrency project created by "mob programming" at a meetup
Rust
1
star
79

crapyesod

Haskell
1
star
80

semiquandle

Experiments in classification
Python
1
star
81

mathnotes

Graduate mathematics notes in TeX
1
star
82

cmsis_nucleo

Experiments with CMSIS (+device family pack) and RTOS with static allocation
C
1
star
83

enigma

Totally random dynamic CSS
JavaScript
1
star
84

preview-ics

Preview iCal invitations from the command line (or mutt)
1
star
85

heroku-buildpack-ghc-test-yesod

Test yesod server deployment
CSS
1
star
86

motif

Trying examples from "Motif Programming" by Marshall Brain
C
1
star
87

heroku-buildpack-ghc-test-snap

Test snap server deployment
Haskell
1
star
88

slow-warp

Why isn't warp responding concurrently?
Haskell
1
star
89

decaying-accumulator

A number that tends toward zero but can be nudged
JavaScript
1
star
90

githhub-care-package

Daily list of repos that need your help
1
star