Limit number of links to show in custom paging - javascript

Now with my code i see all pages, but i want to limit the number of links.
If i have 10 pages, but i want to see only five:
1 2 3 4 5,
5 6 7 8 9.
How can i do that? This is plunk demo on part of my code
This is my controller:
var booksController = function () {
function all(context) {
var size = 2,
page = +context.params['page'] || 0;
templates.get('books')
.then(function (template) {
var booksRef = firebase.database().ref('books');
booksRef = booksRef.orderByChild('timestamp');
booksRef.on('value', function (snapshot) {
this.data = [];
snapshot.forEach(function (child) {
this.data.push(child.val());
}.bind(this));
var pagesLen = Math.ceil(data.length / size),
pages = [];
for (var i = 0; i < pagesLen; i+= 1) {
pages.push({
page: i,
displayPage: i + 1
});
}
data = data.slice(page * size, (page + 1) * size);
context.$element().html(template({
books: data,
pages: pages
}));
});
});
}
return { all: all };
}();
And my hadlebars template:
<section id="primary-content">
<div class="wrapper">
<h1 class="above">Books: </h1>
{{#each books}}
<h1>{{title}}</h1>
{{/each}}
<div id="medium">
</div> {{!--end medium--}}
<ul class="pagination">
{{#pages}}
<li>
<a class="btn btn-sm btn-default" href="#/books/{{page}}">{{displayPage}}</a>
</li>
{{/pages}}
</ul>
</div>

Related

Limiting The Number of Shown Pages on The Pagination

I'm trying to make a pagination for my .pdf file gallery.
I'm using a free pagination template I found online. It works fine but the problem is it creates infinite page numbers.
For example, if I have 100 documents and display 4 per page; the pagination goes from 1-20 and shows them all.
I want it to show 3 at a time, not all of them.
I want something like this: "< 1 ... 5 6 7 ... 20 >" (will change of course each time the page changes).
Right now it's like this: "< 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 >"
Can you guys help me out? Thanks.
HTML:
<ul class="tilesWrap" id="paginated-list" data-current-page="1" aria-live="polite">
<li>
<h2>1</h2>
<h3>Ekim 1. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>2</h2>
<h3>Ekim 2. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>3</h2>
<h3>Ekim 3. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>4</h2>
<h3>Ekim 4. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>1</h2>
<h3>Eylül 1. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>2</h2>
<h3>Eylül 2. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>3</h2>
<h3>Eylül 3. Hafta</h3>
<button>İndir</button>
</li>
<li>
<h2>4</h2>
<h3>Eylül 4. Hafta</h3>
<button>İndir</button>
</li>
</ul>
<nav class="pagination-container">
<button class="pagination-button" id="prev-button" aria-label="Previous page" title="Previous page">
<
</button>
<div class="pagination-numbers" id="pagination-numbers">
</div>
<button class="pagination-button" id="next-button" aria-label="Next page" title="Next page">
>
</button>
</nav>
Java:
<script type="text/javascript">
const paginationNumbers = document.getElementById("pagination-numbers");
const paginatedList = document.getElementById("paginated-list");
const listItems = paginatedList.querySelectorAll("li");
const nextButton = document.getElementById("next-button");
const prevButton = document.getElementById("prev-button");
const paginationLimit = 4;
const pageCount = Math.ceil(listItems.length / paginationLimit);
let currentPage = 1;
const disableButton = (button) => {
button.classList.add("disabled");
button.setAttribute("disabled", true);
};
const enableButton = (button) => {
button.classList.remove("disabled");
button.removeAttribute("disabled");
};
const handlePageButtonsStatus = () => {
if (currentPage === 1) {
disableButton(prevButton);
} else {
enableButton(prevButton);
}
if (pageCount === currentPage) {
disableButton(nextButton);
} else {
enableButton(nextButton);
}
};
const handleActivePageNumber = () => {
document.querySelectorAll(".pagination-number").forEach((button) => {
button.classList.remove("active");
const pageIndex = Number(button.getAttribute("page-index"));
if (pageIndex == currentPage) {
button.classList.add("active");
}
});
};
const appendPageNumber = (index) => {
const pageNumber = document.createElement("button");
pageNumber.className = "pagination-number";
pageNumber.innerHTML = index;
pageNumber.setAttribute("page-index", index);
pageNumber.setAttribute("aria-label", "Page " + index);
paginationNumbers.appendChild(pageNumber);
};
const getPaginationNumbers = () => {
for (let i = 1; i <= pageCount; i++) {
appendPageNumber(i);
}
};
const setCurrentPage = (pageNum) => {
currentPage = pageNum;
handleActivePageNumber();
handlePageButtonsStatus();
const prevRange = (pageNum - 1) * paginationLimit;
const currRange = pageNum * paginationLimit;
listItems.forEach((item, index) => {
item.classList.add("hidden");
if (index >= prevRange && index < currRange) {
item.classList.remove("hidden");
}
});
};
window.addEventListener("load", () => {
getPaginationNumbers();
setCurrentPage(1);
prevButton.addEventListener("click", () => {
setCurrentPage(currentPage - 1);
});
nextButton.addEventListener("click", () => {
setCurrentPage(currentPage + 1);
});
document.querySelectorAll(".pagination-number").forEach((button) => {
const pageIndex = Number(button.getAttribute("page-index"));
if (pageIndex) {
button.addEventListener("click", () => {
setCurrentPage(pageIndex);
});
}
});
});</script>
I am trying to build a pagination that works properly as I want it to.
Please use the following pagination :
$_GET["page"] is the page you want to see
totalpages (now 15) is the total number of pages
offset is the number of pages (1+offset * 2) you want to display before and after the Ellipses (if 1 it means (1+1 * 2) = 3 pages, if 2 it means (1+2 * 2)= 5 pages)
<style>
.pagination {
text-decoration:none;
color:black;
font-family:arial;
font-size:12px;
}
</style>
<script>
var totalpages=15;
var currentpage=<?php echo $_GET["page"]; ?>;
var offset=1;
var offsetnum=(offset*2) +1;
var index=0;
var index0=0;
var starttag="<a class=pagination href='testpage.php?page=";
var endtag="</a>";
if (totalpages >0) {
index0=currentpage-1;
if (index0 <1) { index0=1; }
document.write(starttag+index0+"'>"+"<" + endtag + " ");
if (totalpages <=(offsetnum+2)) {
for (index =1; index <=totalpages; index++) {
if (index !=currentpage){
document.write(starttag+index+"'>"+index + endtag + " ");
}else{
document.write("<B>"+starttag+index+"'>"+index + endtag + "</B> ");
}
}
} else {
if (currentpage<=(1+offset)) {
var startpage=2;
var endpage=2+(offsetnum)-1;
} else {
if (currentpage>=(totalpages-offset)) {
var startpage=(totalpages-1)-(offset*2);
var endpage=(totalpages-1);
} else {
var startpage=currentpage-offset;
var endpage=currentpage+offset;
}
}
if (currentpage!=1){
document.write(starttag+1+"'>1" + endtag + " ");
}else{
document.write("<B>"+starttag+1+"'>1" + endtag+"</B>" + " ");
}
if (startpage>2) document.write(".. ");
for (index =startpage; index <=endpage; index++) {
if (currentpage!=index){
document.write(starttag+index+"'>" + index + endtag + " ");
}else{
document.write("<B>" +starttag+index+"'>" + index + endtag + "</B> ");
}
}
if (endpage < (totalpages-1)) document.write(".. ");
if (currentpage!=totalpages){
document.write(starttag+totalpages+"'>" + totalpages + endtag + " ");
}else{
document.write("<B>"+starttag+totalpages+"'>" + totalpages + endtag + "</B> ");
}
}
index0=currentpage+1;
if (index0 >totalpages) { index0=totalpages; }
document.write(starttag+index0+"'>"+">" + endtag + " ");
}
</script>
Fully working sandbox link:
http://www.createchhk.com/SOanswers/testpage.php?page=10

Angular 4 shopping cart functionality onclick to render text

i am new to angular 4 i want to develop a shopping cart functionality with some different render functionality in html. i can't able to find any solution till now.
already tried with jquery append function but it wont work in edit functionality in feature.
Below gif image shows my requirement
if i click any catagory it will directly append to top of the list with selected catagory.
Then if i click another catagory for same person it will apply after i click apply button
component.html
<ul class="selected-friends" id="appendtext">
</ul>
<ul class="list-friends" id="listFriends">
<div *ngFor="let data of result" [attr.id]="'FriendList' + data.id" #item>
<li class="checkedCatagory">
<div class="sf-left">
<h3>{{data.fullName}}</h3>
<span id="appendCatagoryList"></span>
</div>
<div class="sf-right">
<div class="edit-con sf-icon" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<i class="fa fa-list" aria-hidden="true"></i>
</div>
<div class="del-con sf-icon" [attr.id]="'#list' + data.id" (click)="delete(data.id)">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</div>
</div>
</li>
<!-- Main List started -->
<li class="mainlistname" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<label class="catagory_list" [attr.for]="data.id"><input type="checkbox" [attr.id]="data.id" [attr.value]="data.id">
{{data.fullName}}</label>
</li>
<ul class="sub-friends-list collapse" [attr.id]="'list'+data.id">
<p class="mainlistname">Assign Category to this participant</p>
<p class="checkedCatagory">Edit or Assign another category to this participant</p>
<li *ngFor="let catagoryDetail of catagoryList">
<label class="catagory_list">
<input type="checkbox" class="catagory_list_checkbox" (click)="resize(data.id, catagoryDetail.id);addToCart(data.id,catagoryDetail.id,data.fullName,catagoryDetail.title)" [value]="catagoryDetail.id" [attr.id]="'catagoryId'+catagoryDetail.id">
<span [attr.id]="'catagoryName'+catagoryDetail.id">{{catagoryDetail.title}}</span>
<span class="pull-right fnt-16">AED</span>
<span class="pull-right fnt-16" id="'fee'+catagoryDetail.id">{{catagoryDetail.fee}}</span>
<!-- <p>18-99 Years Male/Female</p> -->
<p *ngIf="catagoryDetail.gender === 1">{{catagoryDetail.ageMinMale}}-{{catagoryDetail.ageMaxMale}} Years Male</p>
<p *ngIf="catagoryDetail.gender === 2">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Female</p>
<p *ngIf="catagoryDetail.gender === 3">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Male/Female</p>
</label>
<span class="checkedCatagoryhidden">
<p *ngFor="let catagorySelected of catagoryList" [attr.id]="'catagorySelected'+catagorySelected.id">
{{catagorySelected.title}} :
<span *ngIf="catagorySelected.gender === 1">{{catagorySelected.ageMinMale}}-{{catagorySelected.ageMaxMale}} Years Male</span>
<span *ngIf="catagorySelected.gender === 2">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Female</span>
<span *ngIf="catagorySelected.gender === 3">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Male/Female</span>
<span class="pull-right fnt-16">AED {{catagorySelected.fee}}</span>
</p>
</span>
</li>
<li class="checkedCatagory" class="apply checkedCatagory quantity">
<span class="quantity_catagory">Qty: <span [attr.id]="'sectionquantity'+data.id"></span></span>
<span class="catagory_amount">Total: AED <span [attr.id]="'sectionprize'+data.id"></span></span>
<button class="btnapplyqnty">Apply</button>
</li>
</ul>
</div>
</ul>
component.ts
addToCart(id, catagoryId, fullName, catTitle){
var currentUserObj = <any>{};
var self = this;
var sum;
currentUserObj[id] = {};
currentUserObj[id].participantid = id;
currentUserObj[id].participantName = fullName;
// console.log(fullName)
this.cart.cartItems[id] = {};
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
var totalPrize = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
var currentCatagoryName = jQuery('.catagory_list input:checked+#catagoryName'+catagoryId).text();
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryName'].push(jQuery(this).next('').text());
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
currentUserObj[id].participantTotalPrize = sum;
console.log('sum',sum)
this.saveCart();
} else {
var currentCategoryId;
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
currentCategoryId = jQuery(this).val();
currentUserObj[id]['categoryName'].push(jQuery(this).next().text());
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].participantTotalPrize = sum;
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
if(currentUserObj[id].quantity === 0) {
console.log("completed delete", this.cart.cartItems[id])
delete self.cart.cartItems[id];
}
this.saveCart();
}
}
add(a, b) {
return a + b;
}
saveCart() {
if (window.localStorage) {
console.log("tfgb",this.cart);
sessionStorage.setItem('cart',JSON.stringify(this.cart));
}
}
resize(id, catagoryId) {
let navObj = this;
var appendSelectedCatagory = document.getElementById('appendtext');
jQuery(appendSelectedCatagory).prepend(jQuery('#FriendList'+id));
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
this.displaySelectedList(id, catagoryId);
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize);
jQuery('#sectionquantity'+id).html(navObj.quantity);
})
})
} else {
this.eventChecked -= 1;
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize)
jQuery('#sectionquantity'+id).html(navObj.quantity)
})
})
this.checkedCatagory.pop(catagoryId);
let checkBoxList = '#appendtext #list'+id;
if(jQuery(checkBoxList+' :checkbox:checked').length == 0){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
sessionStorage.removeItem(id);
}
}
}
displaySelectedList(id, catagoryId){
this.eventChecked += 1;
let getselectList = sessionStorage.getItem('selectedFriends');
jQuery('#appendCatagoryList').append(jQuery('#catagorySelected'+catagoryId))
}
delete(id){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
console.log('asdasdsa',id);
//this.quantity = 0;
sessionStorage.removeItem(id);
}

How to split two items inside a JSON array in angular

This is my code:
$scope.center_name = [];
$scope.stats = ["Stats"];
$scope.totMemCenterData = [];
var query = "SELECT count(*) as tot_mem, centers.name as center_name FROM mem_groups "
+ "INNER JOIN centers ON mem_groups.center_id=centers.id GROUP BY centers.id";
$cordovaSQLite.execute(db, query, [])
.then(function(res){
if (res.rows.length > 0) {
for (var i=0; i < res.rows.length; i++) {
$scope.totMemCenterData = res.rows.item(i);
console.log(JSON.stringify($scope.totMemCenterData));
}
}
}, function(err){
// $cordovaToast.showShortBottom('Something Went Wrong').then(function(success){}, function(err){});
console.log(err.message);
});
This is the result of console.log(JSON.stringify($scope.totMemCenterData)); :
{"center_name":"AFG - ANONANG","tot_mem":6}
{"center_name":"BAM - BUENAVISTA","tot_mem":3}
{"center_name":"GHT - TAGAS","tot_mem":2}
I want to put all center_names in one array also the tot_mem on another array. I want it to be like:
Centers: "AFG - ANONANG", "BAM - BUENAVISTA", "GHT - TAGAS"
Tot_mem: 6, 3, 2
I'm gonna put those values on a chart. Centers on the x-axis and tot_mem on the y-axis
You can do this,
$scope.center_names = [];
$scope.tot_mem = [];
angular.forEach($scope.sampleTest, function(key, value) {
$scope.center_names.push(key["center_name"]);
$scope.tot_mem.push(key["tot_mem"]);
});
DEMO
var app = angular.module('sampleApp', []);
app.controller('myCtrl', function($scope) {
$scope.sampleTest = [{
"center_name": "AFG - ANONANG",
"tot_mem": 6
}, {
"center_name": "BAM - BUENAVISTA",
"tot_mem": 3
}, {
"center_name": "GHT - TAGAS",
"tot_mem": 2
}];
$scope.center_names = [];
$scope.tot_mem = [];
angular.forEach($scope.sampleTest, function(key, value) {
$scope.center_names.push(key["center_name"]);
$scope.tot_mem.push(key["tot_mem"]);
});
});
<!DOCTYPE html>
<html ng-app="sampleApp" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<h1> Center names </h1>
<div ng-repeat="item in center_names">
{{item}}
</div>
<h1> Total memory </h1>
<div ng-repeat="tot in tot_mem">
{{tot}}
</div>
</body>
</html>
Some Observations :
TypeError: res.rows.item is not a function
So, use this res.rows.item[i] instead of res.rows.item(i).
Why JSON.stringify ? As you have to iterate each object to create two different arrays based on the keys. So, leave $scope.totMemCenterData as it is.
Instead of checking the length of res.rows.length check the length of items(res.rows.item.length) as you are going to iterate items.
Working demo :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
var res = {
"rows": {
"item": [{
"center_name": "AFG - ANONANG",
"tot_mem": 6
}, {
"center_name": "BAM - BUENAVISTA",
"tot_mem": 3
}, {
"center_name": "GHT - TAGAS",
"tot_mem": 2
}]
}
};
$scope.center_names = [];
$scope.tot_mem = [];
for (var i=0; i < res.rows.item.length; i++) {
$scope.totMemCenterData = res.rows.item[i];
$scope.center_names.push($scope.totMemCenterData.center_name);
$scope.tot_mem.push($scope.totMemCenterData.tot_mem);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<b>Center Names :</b>
<div ng-repeat="names in center_names">
{{names}}
</div>
<b>Total Mem :</b>
<div ng-repeat="item in tot_mem">
{{item}}
</div>
</div>

How can I show next 15 items in ng-repeat?

I am currently using angular ng-repeat.
When a user clicks a button that says "Next 15", I would like to show next 15 items.
I don't want to pop items from array, I would just like to hide first 15, and limit show to just the next 15.
Also, when the user clicks "Prev 15", I would like to show just the previous 15 items.
Here is what I have so far:
HTML:
<div ng-controller="ctrlIndex as vm">
<ul ng-repeat=" item in vm.items | limitTo: 15 * vm.page
| limitTo: 15 * vm.page < count ? limitTo: 15 * vm.page : 15 - (15 * vm.page - count)"/>
<li>{{ item }}</li>
</ul>
<div><button ng-click="vm.next()">Next 15</button></div>
<div><button ng-click="vm.back()">Prev 15</button></div>
Javascript:
var app = angular.module('app', []);
3app.controller('ctrlIndex', function(){
var vm = this;
vm.numRecords = 15;
vm.page = 1;
vm.items = []
for (var i = 0; i < 1000000; ++i) {
vm.items.push('item : ' + i);
}
vm.next = function(){
vm.page = vm.page + 1;
};
vm.back = function(){
vm.page = vm.page - 1;
};
});
Here you go - Plunker
Markup
<body ng-app="app">
<div ng-controller="ctrlIndex as vm">
<ul ng-repeat="item in vm.items track by $index"
ng-show="(($index < (vm.page * vm.numRecords)) && ($index >= ((vm.page - 1) * vm.numRecords)))">
<li>{{ item }}</li>
</ul>
<div><button ng-click="vm.next()">Next 15</button></div>
<div><button ng-click="vm.back()">Prev 15</button></div>
</div>
</body>
Something like the following will allow you to keep your view tidy and your logic testable:
// controller
var vm = this;
vm.numRecords = 15;
vm.page = 0;
vm.items = [];
vm.data = {};
vm.data.shownItems = [];
vm.limit = 100;
vm.maxPages = Math.floor(vm.limit / vm.numRecords);
for (var i = 0; i < vm.limit; ++i) {
vm.items.push('item : ' + i);
}
vm.data.shownItems = vm.items.slice(0, this.numRecords);
vm.next = function() {
if (vm.page >= vm.maxPages) {
return
}
vm.page += 1;
var begin = vm.page * vm.numRecords;
var end = begin + vm.numRecords;
vm.data.shownItems = vm.items.slice(begin, end);
};
vm.back = function() {
if (vm.page <= 0) {
return
}
vm.page -= 1;
var begin = vm.page * vm.numRecords;
var end = begin + vm.numRecords;
vm.data.shownItems = vm.items.slice(begin, end);
};
// view
<ul ng-repeat="item in vm.data.shownItems">
<li>{{ item }}</li>
</ul>
Plunker

Backbone pagination 10 at a time

Im building an pagination in backbone. The problem is that the amount of pages has grown and are now that many that it ruins the layout of the site. So i want to implement a functionality where i can render lets say the first 10 pages and then with a next/prev button control which page numbers should be shown. But always only show 10 pages like so:
< 1 2 3 4 5 6 7 8 9 10 >
< 2 3 4 5 6 7 8 9 10 11 >
So now i append this to my pagination (its all pages)
updateTotal: function () {
var self = this;
self.totalModel.fetch({
success:function(model,response) {
var total = response.data; //all iems
var p = total/self.perPage;
var r = total-Math.round(p)
self.pagination = _.template($("#pagination_template").html(), {
pages:Math.ceil(p)
});
self.render();
}
});
},
This is how i print it out in html (underscore.js)
<script type="text/template" id="pagination_template">
<section class="pagination">
<ul>
<% for (var i = 0; i < pages; i++) { %>
<li>
<a href="#" data-offset="<%= i*9 %>" data-page="<%= i+1 %>">
<%= i+1 %>
</a>
</li>
<% } %>
</ul>
<div class="paging prev">◄</div>
<div class="paging next">►</div>
</section>
</script>
I have a variable the represents the current page and i know the total amount of pages. But i dont know how to implement this that i describes as my problem.
Anyone knows how to do this and can come with an example? Would be very appreciated!
You can do it like this :
updateTotal: function () {
var self = this;
self.totalModel.fetch({
success:function(model,response) {
var total = response.data; //all iems
var p = total/self.perPage;
var r = total-Math.round(p);
var c = ... // current page
self.pagination = _.template($("#pagination_template").html(), {
pages:Math.ceil(p),
current: c
});
self.render();
}
});
},
And the html
<script type="text/template" id="pagination_template">
<section class="pagination">
<ul>
<%
var renderPage;
for (var i = 1; i <= pages; i++) {
renderPage = false;
if (pages < 10) {
renderPage = true;
} else {
if (current <= 5) {
if (i < 10) {
renderPage = true;
}
} else if (current <= pages - 5) {
if ((current - 5) < i || (current + 5) > i) {
renderPage = true;
}
} else {
if ((pages - 9) < i) {
renderPage = true;
}
}
};
if (renderPage) { %>
<li>
<a href="#" data-offset="<%= i*9 %>" data-page="<%= i %>">
<%= i %>
</a>
</li>
<% }
} %>
</ul>
<div class="paging prev">◄</div>
<div class="paging next">►</div>
</section>
</script>
That will print the current page and the 4 pages before and after.

Categories

Resources