why my when-scrolled not working in following code - javascript

I am trying to load data while the user scrolls down the table on the when-scrolled event but that didn't occur during scroll
i have to implement paging mechanism in my following code
stepwise description
when first-time page load then some data will load
then when user scroll down the next batch of data will load from database and it will continue till the user scroll up
app.service("UserService", function ($http) {
this.getAllUserList = function () {
return $http.get("/FarmerRegistermaster/getAllUser");
};
});
app.directive('whenScrolled', function () {
return function (scope, elm, attr) {
var raw = elm[0];
//alert(attr);
elm.bind('scroll', function () {
if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
scope.$apply(attr.whenScrolled);
}
});
};
});
app.controller('UserCtrl', function ($scope, UserService) {
//GetAll();
$scope.loaderMore = false;
$scope.scrollended = false;
var IsPaging = 0;
var UserID = 1;
var page = 1;
var PageSize = 20;
var inCallback = false;
var totalData = 0;
//******=========Get All Data with Paging=========******
$scope.loadData = function (IsPaging) {
alert("When Scrolled " + IsPaging);
var geturl = '/FarmerRegistermaster/getAllUser';
if (IsPaging === 1) {
//debugger;
IsPaging = 1;
if (page > -1 && !inCallback) {
inCallback = true;
page++;
$scope.loaderMore = true;
$scope.LoadMessage = ' Loading page ' + page + ' of ' + PageSize + ' data...';
$scope.result = "color-green";
var getUser = UserService.getAllUserList();
getUser.then(function (response) {
$scope.UserList = response.data;
}, function () {
$.notify("Error to load data...", "error");
});
var getUser = UserService.getAllUserList();
getUser.then(function (response) {
$scope.UserList.push(response.data);
}, function () {
$.notify("Error to load data...", "error");
});
}
} //unlimited load data while scroll
else {
//debugger;
IsPaging = 0;
$scope.loaderMore = true;
$scope.LoadMessage = 'Loading page ' + page + ' of ' + PageSize + ' data...';
$scope.result = "color-green";
var getUser = UserService.getAllUserList();
getUser.then(function (response) {
$scope.UserList = response.data;
}, function () {
$.notify("Error to load data...", "error");
});
} //default load data while pageload
};
$scope.loadData();
});
<div ng-controller="UserCtrl" class="panel panel-headline">
<section class="panel">
<header class="panel-heading">
<center><b>User List</b></center>
</header>
<div class="panel-body">
<div class="box box-primary box-body table-responsive widget-content content_scroll"
when-scrolled="loadData(1)">
<table class=" table table-striped table-bordered " cellspacing=" 0">
<thead>
<tr>
<th>ID</th>
<th>USER NAME</th>
<th>MOBILE NO</th>
<th>EMAIL</th>
<th>REG DATE</th>
<th>STATUS</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in UserList >
<td>{{user.FARMER_ID}}</td>
<td>{{user.FARMER_NAME}}</td>
<td>{{user.MOBILE_NO}}</td>
<td>{{user.EMAIL_ID}}</td>
<td>{{user.REG_DATE | jsonDate}}</td>
<td>
{{user.STATUS}}
</td>
<td>
</td>
</tr>
</tbody>
</table>
<div class="loadmore">
<div ng-show="loaderMore" ng-class="result">
<imgsrc ="~/Areas/Crm/Content/img/ng-loader.gif" />{{LoadMessage}}
</div>
<div ng-show="scrollended" ng-class="result">
{{LoadMessage}}
</div>
</div>
</div>
</div>
</section>
</div>
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet" />
#section Scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="~/AngularJS/DateFilter.js"></script>
<script src="~/AngularJS/UserCtrl.js"></script>
}
<script>
$(document).ready(function () {
$('#dataTable').DataTable({
"paging": true,
"ordering": true,
"info": true
});
});
</script>
when the user scrolled then the reloadData method should be called every time and data is to be fetched from the database

Related

Search still works after deleting a user + cells keep being created without an input

been working on some basic contacts app and got stuck in two places. Cells keep being created in the table even if there's no input (I've tried if statements) + after deleting a contact I can still search for it. How to remove it from the database? Is it possible to make the create button appear after all the fields have input in it? How can I remove the elements from db array after deleting the cells?
let db = [];
let contact = {};
// ADD CONTACT
$(document).ready(function() {
$("#create-contact").on("click", function(event) {
event.preventDefault();
contact.firstName = $('#name').val();
contact.surname = $('#surname').val();
contact.phone = $("#phone").val();
contact.address = $("#address").val();
let row = document.createElement("tr");
$("table").append(row);
let cell1 = document.createElement("td");
let cell2 = document.createElement("td");
let cell3 = document.createElement("td");
let cell4 = document.createElement("td");
let dltBtn = document.createElement("button");
/* ^ https://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent
Fastest method */
$(dltBtn).text("X")
.css("width", "8.5rem")
.css("color", "white")
.css("background-color", "black")
.attr("class", "dltBtn");
$(cell1).html(contact.firstName);
$(cell2).html(contact.surname);
$(cell3).html(contact.phone);
$(cell4).html(contact.address);
row.append(cell1, cell2, cell3, cell4,dltBtn);
db.push(contact.firstName, contact.surname, contact.phone, contact.address);
console.log(db);
$('.dltBtn').on('click', function(event) {
event.preventDefault();
row.remove(dltBtn)
.deleteCell();
});
});
// SEARCH
function search(name) {
for (i = 0; i < db.length; i++) {
if (!isNaN(name) && db[i] === name) {
return db[i-2] + " " + db[i-1] + " " + db[i] + " " + db[i+1];
}
if (db[i].toUpperCase() === name.toUpperCase()) {
return db[i] + " " + db[i+1] + " " + db[i+2] + " " + db[i+3];
}
$("#found").text("User not found!");
}
};
$('.searchbutton').on('click', function(event) {
event.preventDefault();
var findUserName = $('#query').val();
var userFound = search(findUserName);
$("#found").text(userFound);
console.log(db);
});
});
This example might be more complex than you are needing. Consider creating a db Object with built in functions.
$(function() {
var db = {
content: [],
headers: [
"First Name",
"Last Name",
"Phone",
"Address",
" "
],
tableRef: null,
insert: function(row) {
this.content.push(row);
this._drawTable();
},
delete: function(row_id) {
this.content.splice(row_id, 1);
this._drawTable();
},
search: function(term) {
if (term == undefined || term == "") {
return false;
}
var table = $(this.tableRef);
$("tbody tr", table).hide().each(function(i, row) {
if ($("td:eq(0)", row).text().toLowerCase().indexOf(term.toLowerCase()) >= 0) {
$(row).show();
}
});
},
_getContent: function(id) {
this.tableRef = id;
var table = $(id);
var headers = [];
var rows = [];
$("thead th", table).each(function(i, h) {
headers.push($(h).text());
});
this.headers = headers;
$("tbody tr", table).each(function(i, r) {
rows.push({
firstName: $("td:eq(0)", r).text(),
surName: $("td:eq(1)", r).text(),
phone: $("td:eq(2)", r).text(),
address: $("td:eq(3)", r).text()
});
});
this.content = rows;
console.log("Content collected from " + this.tableRef, this.content.length + " rows.");
},
_drawTable: function() {
var table;
if ($(this.tableRef).length) {
table = $(this.tableRef);
$("tbody tr", table).remove();
} else {
this.tableRef = "#contacts";
table = $("<table>", {
id: "contacts"
}).appendTo("body");
$("<thead>").appendTo(table);
$("<tr>").appendTo($("thead", table));
$.each(this.headers, function(i, h) {
$("<th>").html(h).appentTo($("thead > tr", table));
});
$("<tbody>").appendTo(table);
}
var row;
$.each(this.content, function(i, r) {
row = $("<tr>").appendTo($("tbody", table));
$.each(r, function(j, c) {
$("<td>").html(c).appendTo(row);
});
});
console.log("Table Drawn", this.content.length + " rows");
}
};
db._getContent("#contacts");
$("#contacts").on("click", ".dlt-btn", function(e) {
var rId = $(this).closest("tr").index();
if (confirm("Are you sure you wish to delete this entry?")) {
db.delete(rId);
}
});
$("#add_contact_form").submit(function(event) {
event.preventDefault();
var contact = {
firstName: $("input:eq(0)", this).val(),
surName: $("input:eq(1)", this).val(),
phone: $("input:eq(2)", this).val(),
address: $("input:eq(3)", this).val()
};
db.insert(contact);
this.reset();
});
$("#search_contacts").on("input", "input", function() {
if ($(this).val().length >= 1) {
db.search($(this).val());
} else {
$(db.tableRef).find("tbody tr").show();
}
});
});
#add_contact td,
#add_contact input {
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search_contacts">
Search: <input type="text">
</form>
<table id="contacts" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Homer</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Marge</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Bart</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Lisa</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
<tr>
<td>Maggie</td>
<td>Simpson</td>
<td>(939)-555-0113</td>
<td>742 Evergreen Terrace</td>
<td><button class="dlt-btn">X</button></td>
</tr>
</tbody>
</table>
<form id="add_contact_form">
<table id="add_contact" width="100%">
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td width="30px"> </td>
</tr>
</tbody>
</table>
<button type="submit" id="create-contact">Create Contact</button>
</form>
There are lots of ways to manage Arrays. Please see:
https://www.w3schools.com/jsref/jsref_push.asp
https://www.w3schools.com/jsref/jsref_splice.asp
https://www.w3schools.com/jsref/jsref_indexof_array.asp
Once you adjust the Array you need to either redraw the table or perform the same function to the Table element.
Searching, or in this case, filtering, can be done in a lot of ways too. This is a pretty basic example. You can look at other options if you like.

$(#id).html(content) function to set content to the next column

This is my HTML code:
<div class="row margin-top-3">
<div class="col-sm-7">
<h2>NFTs</h2>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th id = "NFTID">NFT ID</th>
<th id = "NFTNAME">NFT Name</th>
<th id = "NFTCREATOR">Creator</th>
</tr>
</thead>
<tbody id="NFT-rows">
</tbody>
</table>
</div>
</div>
</div>
The following three functions populate the table by column.
The problem is that the third function overwrites the second column instead of the third column.
Also, adding a fourth function will again overwrite the second column.
So, how can I re-write the $(#id).html(content) part to make it populate the next column instead of the second?
setupNFTRows: function() {
console.log("setupNFTrows NFT Array = " + JSON.stringify(NFTs));
console.log("NFT = " + Object.keys(NFTs))
Object.keys(NFTs).forEach(function (NFT) {
console.log("inside setupNFTrows");
$("#NFT-rows").append("<tr><td>" + "NFT_ID_" + NFT + "</td><td id='" + NFTs[NFT] + "'></td></tr>");
});
},
populateNFTNames: function() {
console.log("inside populateNFTNames")
let NFTIDs = Object.keys(NFTs);
console.log("NFTIDs = " + NFTIDs)
for(var i=0; i < NFTIDs.length; i++) {
let nftid = NFTIDs[i];
NFTContract.deployed().then(function(contractInstance) {
contractInstance.getNFTname.call(nftid).then(function(v) {
$("#" + NFTs[nftid]).html(v.toString());
})
})
}
},
populateCreators: function() {
let NFTIDs = Object.keys(NFTs);
for(var i=0; i < NFTIDs.length; i++) {
let nftid = NFTIDs[i];
NFTContract.deployed().then(function(contractInstance) {
contractInstance.getCreator.call(nftid).then(function(v) {
$("#" + NFTs[nftid]).html(v.toString());
})
})
}
},
This is because data tables are populated a row at a time, not a column at a time. The best way to approach this would be to zip your data together into a cohesive set to fill the rows:
const getNFTNames = (id) => {
NFTContract.deployed().then(contractInstance => {
contractInstance.getNFTname.call(nftid).then(v => {
return v.toString();
});
});
};
const getCreators = (id) => {
NFTContract.deployed().then(contractInstance => {
contractInstance.getCreator.call(nftid).then(v => {
return v.toString();
});
});
};
const setupNFTRows = () => {
Object.keys(NFTs).forEach(id => {
$("#NFT-rows").append(
`<tr id='NFT_ID_${id}'>
<td>NFT_ID_${id}</td>
<td>${getNFTNames(id)}</td>
<td>${getCreators(id)}</td>
</tr>`);
});
};

How have I broken this Todo list in ReactJS code?

An earlier draft of code to handle a Todo list, with fewer features, works:
{
return 0;
}
});
return (
<div id="Todo">
<h1>Todo</h1>
<form onSubmit={that.handleSubmit}>
<table>
{table_rows}
<tfoot>
<textarea name='todo-textarea' id='todo-textarea'
onChange={that.onChange}></textarea><br />
<button>{'Add activity'}</button>
</tfoot>
</table>
</form>
</div>
);
}
});
My present version is getting an InvariantViolation:
react-with-addons.js:20237 Uncaught Error: Invariant Violation: findComponentRoot(..., .0.1.1.0.0:0:0.0:1.0): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an parent. Try inspecting the child nodes of the element with React ID ``.
The present code is:
var Todo = React.createClass(
{
mixins: [React.addons.LinkedStateMixin],
getInitialState: function()
{
var result = parse(initial_todo, {
'next_todo_index': 1,
'items': [],
'text': ''
});
return result;
},
handle_change: function(event)
{
var that = this;
var address = jQuery(event.target).attr('data-index').split('.', 2);
var identifier = parseInt(address[0], 10);
for(var candidate = 0; candidate < this.state.next_todo_index;
candidate += 1)
{
if (parseInt(jQuery(this.state.items[candidate]).attr('index'), 10)
=== identifier)
{
(this.state.items[candidate][address[1]] =
!this.state.items[candidate][address[1]]);
save('Todo', this.state);
}
}
that.render();
},
handleSubmit: function(event)
{
event.preventDefault();
var new_item = get_todo_item(this);
new_item.description = this.state.text;
this.state.items.unshift(new_item);
document.getElementById('todo-textarea').value = '';
save('Todo', this.state);
if (!one_shot)
{
one_shot = true;
}
// this.forceUpdate();
// React.render(<Todo />,
// document.getElementById('Todo'));
},
onChange: function(event)
{
this.setState({text: event.target.value});
},
render: function()
{
var that = this;
var table_rows = [];
var display_item_details = function(label, item)
{
var html_id = item.index + '.' + label;
return (
<td className={label} title={label}>
<input onChange={that.handle_change} data-index={html_id}
className={label} type="checkbox"
defaultChecked={item[label]} />
</td>
);
};
var display_item = function(item)
{
var rendered_nodes = [];
if (item['Completed'] || item['Delete'] || item['Invisible'])
{
return '';
}
else
{
for(var index = 0; index < todo_item_names.length;
index += 1)
{
rendered_nodes.push(
display_item_details(todo_item_names[index], item)
);
}
return (
<tr>{rendered_nodes}
<td className="description" dangerouslySetInnerHTML={{__html:
converter.makeHtml(item.description)}} /></tr>
);
}
};
table_rows.push(that.state.items.map(display_item));
table_rows.sort(function(a, b)
{
if (a.index > b.index)
{
return 1;
}
else if (b.index > a.index)
{
return -1;
}
else
{
return 0;
}
});
return (
<div id="Todo">
<h1>Todo</h1>
<form onSubmit={that.handleSubmit}>
<table>
<tbody>
{table_rows}
<tbody>
<tfoot>
<textarea name='todo-textarea' id='todo-textarea'
onChange={that.onChange}></textarea><br />
<button>{'Add activity'}</button>
</tfoot>
</table>
</form>
</div>
);
}
});
How have I broken this?
Do check through your html table structure. Other than the <tbody> fix, the usage of <tfoot> is also invalid markup.
The <tfoot> element can only contain <tr> tags inside.
i.e.
<tfoot>
<tr>
<td>
<textarea name='todo-textarea' id='todo-textarea'
onChange={that.onChange}></textarea><br />
<button>{'Add activity'}</button>
</td>
</tr>
</tfoot>

How to pass html element(table) dynamically to angular directive?

I have html tables which are rendered using ng-repeat, i have to export data of that tables into csv file, I found one directive which does it, it works well for one table and did not works properly when there are multiple tables which are using same directive. When i click on export button then the last processed html table is exported not the required one. Bellow i given my HTML code. Here is PLUNKER
<label for="state" class="control-label col-sm-2"><span class="tag">Select territory:</span></label>
<div class="col-sm-2">
<select ng-model="rtype" ng-options="reportName for (reportName, reportType) in reportTypeOptions" class="form-control" id="rtype"></select>
</div>
</div>
<div class="col-sm-9 " style="margin-top: 30px;" ng-show="userLocations.stateWise">
<a ng-click='csv.generate($event, filename() + ".csv", t1)' href=''><button class="btn btn-default export-btn">Export</button></a>
<table id="t1" ng-table="tableParams1" show-filter="false" class="table table-condensed table-bordered table-striped" ng-show="rtype === 'state'" export-csv='csv'>
<tr ng-repeat="(key, value) in userLocations.stateWise">
<td data-title="'Sr No.'" style="width:3%;">{{ $index + 1 }}</td>
<td data-title="'State'" style="width:5%;">{{ key }} </td>
<td data-title="'Total Users'" style="width:7%;">{{ value }} </td>
</tr>
</table>
<table id="t2" ng-table="tableParams2" show-filter="false" class="table table-condensed table-bordered table-striped" ng-show="rtype === 'dist'" export-csv='csv'>
<tr ng-repeat="(key, value) in userLocations.districtWise">
<td data-title="'Sr No.'" style="width:3%;" style="width:3%;">{{ $index + 1 }}</td>
<td data-title="'State'" style="width:5%;">{{ value.userLocation.state }} </td>
<td data-title="'District'" style="width:7%;">{{ value.userLocation.district }} </td>
<td data-title="'Total Users'" style="width:7%;">{{ value.totalUsers }} </td>
</tr>
</table>
<table id="t3" ng-table="tableParams3" show-filter="false" class="table table-condensed table-bordered table-striped" ng-show="rtype === 'pin'" export-csv='csv'>
<tr ng-repeat="(key, value) in userLocations.pincodeWise">
<td data-title="'Sr No.'" style="width:3%;" style="width:3%;">{{ $index + 1 }}</td>
<td data-title="'State'" style="width:5%;">{{ value.userLocation.state }} </td>
<td data-title="'District'" style="width:7%;">{{ value.userLocation.district }} </td>
<td data-title="'Pincode'" style="width:7%;">{{ value.userLocation.pincode }} </td>
<td data-title="'Total Users'" style="width:7%;">{{ value.totalUsers }} </td>
</tr>
</table>
</div>
` // Angular directive code toexport table
app.directive('exportCsv', ['$parse', '$timeout', 'ngTableEventsChannel', function ($parse, $timeout, ngTableEventsChannel) {
var delimiter = ',';
var header = 'data:text/csv;charset=UTF-8,';
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var data = '';
if (attrs.delimiter) { delimiter = attrs.delimiter; }
function stringify(str) {
return '"' +
str.replace(/^\s\s*/, '').replace(/\s*\s$/, '')
.replace(/"/g,'""') + '"';
}
function parseTable() {
data = '';
var rows = element.find('tr');
angular.forEach(rows, function(row, i) {
var tr = angular.element(row),
tds = tr.find('th'),
rowData = '';
if (tr.hasClass('ng-table-filters')) {
return;
}
if (tds.length === 0) {
tds = tr.find('td');
}
if (i !== 1) {
angular.forEach(tds, function(td) {
rowData += stringify(angular.element(td).text()) + Array.apply(null, Array(td.colSpan)).map(function () { return delimiter; }).join('');
});
rowData = rowData.slice(0, rowData.length - 1);
}
data += rowData + '\n';
});
data = 'sep=' + delimiter + '\n' + data;
}
function download(dataUri, filename, scope) {
var link = document.createElement('a');
link.style.display = 'none';
link.href = dataUri;
link.download = filename;
link.target = '_blank';
$timeout(function () {
try {
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
catch(err) {
if (scope.logError) {
scope.logError('NG Table Export Error saving file on client.');
}
throw(err);
}
}, 0, false);
}
// csv var for calling its method
var csv = {
generate: function(event, filename, table) {
var isNgTable = attrs.ngTable,
table = table || scope.$parent.tableParams,
settings = table ? table.settings() : {},
cnt = table ? table.count() : {},
total = table ? settings.total : {};
if (isNgTable && cnt < total) {
var $off = ngTableEventsChannel.onAfterReloadData(function () {
$off();
$timeout(function () {
parseTable();
table.count(cnt);
table.reload();
download(header + encodeURIComponent(data), filename, scope);
}, 1000, false);
});
table.count(Infinity);
table.reload();
} else {
parseTable();
download(header + encodeURIComponent(data), filename);
}
}
};
$parse(attrs.exportCsv).assign(scope.$parent, csv);
}
};
}]);`
How to give element to directive if element occurs more than once.

AngularJS with AngularUI Bootsrap pagination directive doesn't hide results

I'm trying to use Angular-ui pagination directive for the first time and am confused why it isn't working. I can see the pagination buttons and it properly displays two pages to paginate through since there are 8 results and items-per-page="5" But all my data items are showing and not being hidden to five per page.
controller
dataService.get(uri).then(function (data) {
$scope.testimonials = data;
$scope.totalItems = $scope.testimonials.length;
$scope.currentPage = 1;
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
console.log('Page changed to: ' + $scope.currentPage);
}
});
view
<table class="table table-striped" ng-show="testimonials.length">
<thead>
<th>Name</th>
<th>Message</th>
</thead>
<tbody>
<tr ng-repeat="testimonial in testimonials">
<td>{{testimonial.name}}</td>
<td>{{testimonial.message}}</td>
<td>Edit</td>
<td><button class="btn btn-danger" ng-click="delete(testimonial)">Delete</button></td>
</tr>
</tbody>
<pagination total-items="totalItems" ng-model="currentPage" items-per-page="5" ng-change="pageChanged()"></pagination>
</table>
I appreciate any advice, thanks!
Yo need filter data in your ng-reapeter code below should works
<table class="table table-striped" ng-show="testimonials.length">
<thead>
<th>Name</th>
<th>Message</th>
</thead>
<tbody>
<tr ng-repeat="testimonial in testimonials | startFrom: (currentPage-1)*5| limitTo: 5">
<td>{{testimonial.name}}</td>
<td>{{testimonial.message}}</td>
<td>Edit</td>
<td><button class="btn btn-danger" ng-click="delete(testimonial)">Delete</button></td>
</tr>
</tbody>
<pagination total-items="totalItems" ng-model="currentPage" items-per-page="5" ng-change="pageChanged()"></pagination>
</table>
filter starts from:
app.filter('startFrom', function () {
return function (input, start) {
if (input === undefined || input === null || input.length === 0
|| start === undefined || start === null || start.length === 0 || start === NaN) return [];
start = +start; //parse to int
try {
var result = input.slice(start);
return result;
} catch (e) {
// alert(input);
}
}
});
I can't find the original example I used, but this is what I have in my app.
The filter part isn't important, but the filterProducts object is what gets sliced and shown in your view. Check out the $watch for how it works.
app.controller('ProductController', function($scope, $filter, $routeParams, $rootScope, $location, Products){
$scope.Products = Products;
Products.brandLimit = $routeParams.brandLimit;
Products.brand = $routeParams.brand;
// try to avoid reloading the prod data
if (!Products.products){
Products.getProducts().then(function(data){
Products.products = data.products;
Products.pagination();
});
}else{
Products.pagination();
}
// watch for when the pagination changes
$scope.$watch('Products.currentPage + Products.numPerPage', function() {
var begin = ((Products.currentPage - 1) * Products.numPerPage);
var end = begin + Products.numPerPage;
Products.pagedProducts = Products.filteredProducts.slice(begin, end);
});
});
And in the service:
app.factory('Products', function($http, $filter, $location, $routeParams){
var Products = {
search: '',
searching: false,
filteredProducts: '',
pagedProducts: '',
getProduct: function(id){
delete Products.detail;
$http.get('/product/' + id).then(function(response){
Products.detail = response.data.product;
});
},
getProducts: function(){
return $http.get('/product').then(function(response){
return response.data;
});
},
pagination: function(){
// relies on fulltext filter
this.filteredProducts = $filter('fulltext')(this.products, this.brandLimit);
// set up default values to feed to ui pagination
this.currentPage = 1;
this.numPerPage = 10;
this.maxSize = 10;
// check the length of filtered items based on search or brand clicked (in the URL)
this.totalItems = this.filteredProducts.length;
this.numPages = Math.ceil(this.totalItems / this.numPerPage);
},
brandTitle: function() {
if (this.searching === false || this.brand) {
this.search = '';
return $routeParams.brand + " Products";
} else {
return 'Searching "' + $routeParams.brandLimit + '"';
}
},
searchTerm: function(){
if(this.search){
$location.path("search/" + this.search);
this.searching = true;
}else{
$location.path("/");
this.searching = false;
}
}
};
return Products;
});
And HTML:
<pagination ng-show="Products.numPages" total-items="Products.totalItems" ng-model="Products.currentPage" max-size="Products.maxSize" class="pagination-small" boundary-links="true" rotate="false" num-pages="Products.numPages"></pagination>
<table class="table table-striped">
<tr>
<th>Maker</th>
<th>Title</th>
<th ng-bind="product.priceDealer">Dealer Price</th>
<th>MSRP</th>
</tr>
<tr ng-repeat="product in Products.pagedProducts">
<td>{{product.brand}}</td>
<td>{{product.title}}</td>
<td ng-bind="product.priceDealer | currency"></td>
<td>{{product.msrp | currency:"$"}}<td>
</tr>
</table>
No Need of all that, use attribute of angular UI Bootstrap:
HTML
<pager total-items="totalItems" ng-model="currentPage" items-per-page="itemsPerPage"></pager>
====
and add below code in your controller
===========
$scope.totalItems = $scope.testimonials.length;
$scope.itemsPerPage = 5;
$scope.currentPage = 1;
$scope.$watch('currentPage + itemsPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredtestimonials= $scope.alerts.slice(begin, end);
});
===========
Note that you need to mention ng-repeat="testimonial in filteredtestimonials"
and attribute should be in same scope of where you have used you used ng-repeat
Please let me know if you still face any issue and you can see more examples of this on: http://angular-ui.github.io/bootstrap/#/pagination
Do include :
in your page or layout page and items-per-page will not take direct value, it seems

Categories

Resources