Skip to content

Instantly share code, notes, and snippets.

@pat-eason
Created May 6, 2016 16:01
Show Gist options
  • Save pat-eason/fd419ea559309ed318eaaeff8bc2ce74 to your computer and use it in GitHub Desktop.
Save pat-eason/fd419ea559309ed318eaaeff8bc2ce74 to your computer and use it in GitHub Desktop.
Angular Pagination Factory
app.factory("Pagination",
[
'$filter',
function($filter){
var Pagination = {
data: {
perPage:20,
count: 0,
currentPage: 0,
paginationSet: [],
currentData: [],
data: [],
pagesMin : true,
pages: 0,
pagesMax : false
},
init: function(data, perPage){
var $this = this;
$this.data.perPage = perPage ? perPage : 20;
$this.data.data = data;
$this.data.currentData = data;
$this.data.count = data.length;
$this.goToPage(1);
},
update: function(){
},
/**
* @return updates paginationSet and currentPage
* @return triggers $this.buildButtons
*/
goToPage: function(index){
var $this = this;
var pageStart = ($this.data.perPage * index) - $this.data.perPage;
var pageEnd = $this.data.perPage * index;
$this.data.currentPage = index;
$this.data.paginationSet = $this.data.currentData.slice(pageStart, pageEnd);
$this.buildButtons();
},
/**
* @param: sortOptions @optional object
* {
* type : value,
* reverse : boolean
* }
*
* @param: filterOptions @optional object
* {
* filterName : filterValue,
* ...
* }
*/
updateSort: function(sortOptions, filterOptions){
console.log('updateSort', sortOptions, filterOptions);
var $this = this;
$this.data.currentData = $filter('orderBy')($this.data.data, sortOptions.type, sortOptions.reverse);
_.each(filterOptions, function(v, k){
console.log('Sorting by ' + k + " : " + v);
$this.data.currentData = $filter('filter')($this.data.currentData, v);
});
$this.goToPage(1);
},
/**
* @return updates pagesMin, pages, pagesCurrent, and pagesMax
*/
buildButtons: function(){
var $this = this;
$this.data.pages = Math.ceil( ($this.data.currentData.length / 20) );
if($this.data.currentPage <= 1)
$this.data.pagesMin = true;
else
$this.data.pagesMin = false;
if($this.data.currentPage >= $this.data.pages)
$this.data.pagesMax = true;
else
$this.data.pagesMax = false;
var pageArray = [];
for(i=0; i<$this.data.pages; i++){
pageArray.push(i+1);
}
$this.data.pages = pageArray;
}
};
return Pagination;
}
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment