Skip to content

Instantly share code, notes, and snippets.

@egaumer
Created May 14, 2013 11:20
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save egaumer/5575237 to your computer and use it in GitHub Desktop.
Save egaumer/5575237 to your computer and use it in GitHub Desktop.
Elasticsearch/AngularJS Pagination Example
$scope.pager = {
pageChange: function(pageNum) {
$scope.search(resultPager.get(pageNum));
},
next: function() {
this.pageChange(resultPager.next());
},
prev: function() {
this.pageChange(resultPager.previous());
},
pageClass: function(ind){
return ind+1 === resultPager.current() ? "disabled" : "";
},
prevClass: function() {
return resultPager.current() > 1 ? "" : "disabled";
},
nextClass: function() {
return resultPager.current() < resultPager.total() ? "" : "disabled";
},
pages: function() {
return resultPager.pages(pageMin, pageMax);
}
};
<div class="pagination" ng-model="pager">
<ul>
<li ng-class="pager.prevClass()"><a ng-click="pager.prev()">Prev</a></li>
<li ng-class="pager.pageClass($index)" ng-repeat="page in pager.pages()">
<a ng-click="pager.pageChange(page)">{{page}}</a>
</li>
<li ng-class="pager.nextClass()"><a ng-click="pager.next()">Next</a></li>
</ul>
</div>
ResultPager: function(request, hits) {
var total = Math.ceil(hits / request.size);
total = total === 0 ? 1 : total;
var current = Math.ceil((request.from / request.size) + 1);
return {
total: function() {
return total;
},
current: function() {
return current;
},
next: function() {
var next = current;
if (current < total) {
next = current + 1;
}
return next;
},
previous: function() {
var previous = current;
if (current > 1) {
previous = current - 1;
}
return previous;
},
pages: function(min, max) {
var pages = [],
end = current + min < total ? current + min : total + 1,
start = end - max > 1 ? end - max : 1,
i;
for (i = start; i < end; i++) {
pages.push(i);
}
return pages;
},
get: function(page) {
var start = (page * request.size) - request.size;
return start;
}
};
}
@michael-bouvy
Copy link

Thanks for this useful example. Shall ResultPager be set as a service ?

If so, I'm wondering how to inject request and hits to the service ?

Thanks in advance.

@yuneekguy
Copy link

This looks very lean and neat compared to most implementations I have seen. However, like michael said, is this a service and how do you inject request and hits? Simply put, how do all this piece together. A sample demo would help a great deal.

But thanks. This is really helpful.

@YannBrrd
Copy link

👍 a demo page would be great !

@maiconzucco
Copy link

really, a demo page would be great. thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment