I'm using an Angular UI modal to update the calendar style grid UI. (on a drag and drop style app (using http://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/types)), to e.g. change the date of an order planningslot.
The modal is to provide a manual way of updating and I can’t save until the user hits the Save button.
This is fine (though I suspect it could be better) in updating the data in my parent scope object (scope.WokCentres), i.e. the date changes, great). What I’m stuck on is ‘moving’ the object to it’s new date within the 'calendar style grid'
Below is my JS and view html
JS:
$scope.EditWorkOrder = function (slot, max) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: '/app/WorkOrder/Views/EditWorkOrder.html',
controller: 'EditWorkOrderCtrl as vm',
size: 'lg',
resolve: {
data: function () {
return {
Slot: slot,
Max: max
}
}
}
});
//slotupdate is the returned object from the modal
modalInstance.result.then(function (slotupdate) {
for (var a = 0; a < scope.WorkCentres.length; a++) {
var wcs = scope.WorkCentres[a]
for (var b = 0; b < wcs.WorkOrderDates.length; b++) {
var wcd = wcs.WorkOrderDates[b]
for (var c = 0; c < wcd.PlanningSlots.length; c++) {
var slot = wcd.PlanningSlots[c]
if (slot.Id == slotupdate.Id) {
// This gets hit and updates the appropriate data object from the loop
scope.WorkCentres[a].WorkOrderDates[b].PlanningSlots[c] = slotupdate;
}
}
}
}
}, function () {
// do nothing
// $log.info('Modal dismissed at: ' + new Date());
});
};// END OF MODAL
VIEW:
<div ng-controller="workCentreCtrl as vm">
<div class="row">
<div class="workcentre-left">
<h3>Work Centre</h3>
</div>
<div class="workcentre-right">
<ul>
<li class="date-bar" ng-repeat="workdate in vm.WorkDates">{{workdate |date:'EEEE'}} {{workdate |date:'dd MMM'}}</li>
</ul>
</div>
</div>
<div>
<div class="row" ng-repeat="wc in vm.WorkCentres" ng-model="vm.WorkCentres">
<div class="workcentre-left">
<h5>{{wc.WorkCentreName}}</h5>
<button class="btn btn-default" ng-click="open(wc.WorkCentreId)" type="button">edit</button>
<p ng-if="wc.RouteTime != 0">{{wc.RouteTime}}</p>
</div>
<div class="workcentre-right dndBoxes">
<ul class="orderdate" ng-repeat="date in wc.WorkOrderDates" data-workdate="{{date.OrderDate}}">
<li id="parentorderdate" ng-class="{'four-slot': wc.max == 4, 'eight-slot': wc.max == 8, 'twelve-slot': wc.max == 12,'sixteen-slot': wc.max == 16}">
<ul dnd-list="date.PlanningSlots"
dnd-allowed-types="wc.allowedTypes"
dnd-disable-if="date.PlanningSlots.length >= wc.max"
dnd-dragover="dragoverCallback(event, index, external, type)"
dnd-drop="dropCallback(event, index, item, external, type, 'itemType')"
dnd-inserted="logEvent('Element was inserted at position ' + index, event)">
<li ng-repeat="slot in date.PlanningSlots" ng-model="date.PlanningSlots" ng-if="slot.WorkOrderNumber != '' "
dnd-draggable="slot"
dnd-type="wc.allowedTypes"
dnd-moved="date.PlanningSlots.splice($index, 1)"
dnd-effect-allowed="move" class="slot {{slot.css}}" title="{{slot.WOStatus}}">
<div>{{slot.SlotNumber}}</div>
<div>{{slot.WorkOrderNumber}} - {{slot.ProductDescription}}</div>
<div ng-if="slot.WOStatus != ''"><span class="float-right fa fa-edit fa-2x main-text edit-work-order" ng-click="EditWorkOrder(slot, wc.max)"></span></div>
</li>
<li ng-repeat="slot in date.PlanningSlots" ng-model="date.PlanningSlots" ng-if="slot.SlotBlocked == 'true'"
class="empty-slot">{{slot.SlotBlocked}}
<i class="fa fa-ban fa-2x main-text"></i>
</li>
<li class="dndPlaceholder">Drop work order here
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
Any help many appreciated.
itsdanny
The code in the OP, breaks the model (scope.WorkCentres).
There is an angular.forEach function which doesn't
modalInstance.result.then(function (slotupdate) {
// Remove it
angular.forEach(scope.WorkCentres, function (wc) {
angular.forEach(wc.WorkOrderDates, function (WorkOrderDate) {
angular.forEach(WorkOrderDate.PlanningSlots, function (slot) {
if (slot.Id == slotupdate.Id) {
WorkOrderDate.PlanningSlots.splice(index, 1);
}
})
})
})
// Add it back
angular.forEach(scope.WorkCentres, function (wc) {
if (wc.WorkCentreId == slotupdate.WorkCentreId) {
angular.forEach(wc.WorkOrderDates, function (WorkOrderDate) {
if (WorkOrderDate.OrderDate == slotupdate.OrderDate.getTime()) {
WorkOrderDate.PlanningSlots.push(slotupdate)
return;
}
})
}
})
}
I might actually cry out of joy!
Related
I'm unable to get the radio button checked even with the text matching the radio button value.
`
<div class="well pull-left clearfix" style="margin:5px;width:90px;padding:5px;" data-bind="click: $root.select_litho_layer_definition, css: {'background-highlight': $root.current_litho_layer_definition() === $data}">
<p class="text-center tight-padding no-margin"><strong data-bind="text: layer_name"></strong></p>
<div class="btn-group" style="width:90px">
<button class="btn btn-mini dropdown-toggle" data-toggle="dropdown" style="width:90px">
<span data-bind="text: 'Rev.' + revision"></span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu small-list" data-bind="foreach: $root.litho_layer_name_definitions()[_.indexOf($root.litho_layer_names(), layer_name)]" style="width:90px">
<li><a data-bind="text: 'Rev.' + revision, click: $root.litho_layer_name_select_revision"></a></li>
</ul>
</div>
<!-- ko foreach: exposure_array_names-->
<input type="radio" name="ExposureGroup" value="$parent.layer_name+$data" data-bind="click: $root.litho_layer_name_select_exposure, checked:$root.litho_layer_exposure"/>
<span data-bind="text: $data"></span><br>
<!--/ko-->
</div>
<!-- /ko -->
`
Each of the litho_layer_name_selected_definitions has an array of exposures called exposure_array_names
Now object structure looks like this.
{
"litho_layer_definition_sk": 90000026426,
"exposure_array_names": [
"IF1_EDGE",
"Combined"
],
"layer_name": "3HG",
"revision": 0
}
In the js, I have created an observable object of litho_layer_exposure
self.litho_layer_exposure = ko.observable(true);
self.litho_layer_exposure = ko.computed(function() {
var maskset = self.maskset();
if (!maskset) return [];
var defs = maskset.litho_layer_definitions;
if (_.isEmpty(defs)) return [];
var name = self.current_litho_layer_name();
if (!name) return [];
var revision = self.current_litho_layer_revision();
if (!_.isNumber(revision)) return;
_.reduce(defs, function(memo, d) {
if (d.layer_name === name && d.revision === revision){
memo.push(_.last(d.exposure_array_names));
}
return memo;
}, []);
});
self.litho_layer_exposure.subscribe(function(exposure) {
if (!_.isEmpty(exposure)) self.current_litho_layer_exposure(_.last(exposure));
});
I tried making the below change, which didn't work either
self.litho_layer_exposure = ko.computed({
read: function () {
var maskset = self.maskset();
if (!maskset) return [];
var defs = maskset.litho_layer_definitions;
if (_.isEmpty(defs)) return [];
var name = self.current_litho_layer_name();
if (!name) return [];
var revision = self.current_litho_layer_revision();
if (!_.isNumber(revision)) return;
/*var exposure = self.current_litho_layer_exposure();
if (!exposure) return [];*/
return _.reduce(defs, function(memo, d) {
if (d.layer_name === name && d.revision === revision) memo.push(d.default_exposure_name);
return memo;
}, []);
},
write: function (value) {
//update your self.chosenAge().population value here
self.current_litho_layer_exposure(value);
self.litho_layer_exposure(value);
},
owner: self
});
self.litho_layer_exposure.subscribe(function(exposure) {
if (!_.isEmpty(exposure)) self.current_litho_layer_exposure(_.last(exposure));
});
I´m pretty sure the initial error is
value="$parent.layer_name+$data"
which should lead to all inputs have literally "$parent.layer_name+$data" as value
you probably wanted to use a databinding to fill the attribute
data-bind="attr:{value: $parent.layer_name+$data}, checked: ..."
It is not like it is slow on rendering many entries. The problem is that whenever the $scope.data got updated, it adds the new item first at the end of the element, then reduce it as it match the new $scope.data.
For example:
<div class="list" ng-repeat="entry in data">
<h3>{{entry.title}}</h3>
</div>
This script is updating the $scope.data:
$scope.load = function() {
$scope.data = getDataFromDB();
}
Lets say I have 5 entries inside $scope.data. The entries are:
[
{
id: 1,
title: 1
},
{
id: 2,
title: 2
},
......
]
When the $scope.data already has those entries then got reloaded ($scope.data = getDataFromDB(); being called), the DOM element for about 0.1s - 0.2s has 10 elements (duplicate elements), then after 0.1s - 0.2s it is reduced to 5.
So the problem is that there is delay about 0.1s - 0.2s when updating the ng-repeat DOM. This looks really bad when I implement live search. Whenever it updates from the database, the ng-repeat DOM element got added up every time for a brief millisecond.
How can I make the rendering instant?
EDITED
I will paste all my code here:
The controller:
$scope.search = function (table) {
$scope.currentPage = 1;
$scope.endOfPage = false;
$scope.viewModels = [];
$scope.loadViewModels($scope.orderBy, table);
}
$scope.loadViewModels = function (orderBy, table, cb) {
if (!$scope.endOfPage) {
let searchKey = $scope.page.searchString;
let skip = ($scope.currentPage - 1) * $scope.itemsPerPage;
let searchClause = '';
if (searchKey && searchKey.length > 0) {
let searchArr = [];
$($scope.vmKeys).each((i, key) => {
searchArr.push(key + ` LIKE '%` + searchKey + `%'`);
});
searchClause = `WHERE ` + searchArr.join(' OR ');
}
let sc = `SELECT * FROM ` + table + ` ` + searchClause + ` ` + orderBy +
` LIMIT ` + skip + `, ` + $scope.itemsPerPage;
sqlite.query(sc, rows => {
$scope.$apply(function () {
var data = [];
let loadedCount = 0;
if (rows != null) {
$scope.currentPage += 1;
loadedCount = rows.length;
if (rows.length < $scope.itemsPerPage)
$scope.endOfPage = true
for (var i = 0; i < rows.length; i++) {
let item = rows.item(i);
let returnObject = {};
$($scope.vmKeys).each((i, key) => {
returnObject[key] = item[key];
});
data.push(returnObject);
}
$scope.viewModels = $scope.viewModels.concat(data);
}
else
$scope.endOfPage = true;
if (cb)
cb(loadedCount);
})
});
}
}
The view:
<div id="pageContent" class="root-page" ng-controller="noteController" ng-cloak>
<div class="row note-list" ng-if="showList">
<h3>Notes</h3>
<input ng-model="page.searchString" id="search"
ng-keyup="search('notes')" type="text" class="form-control"
placeholder="Search Notes" style="margin-bottom:10px">
<div class="col-12 note-list-item"
ng-repeat="data in viewModels track by data.id"
ng-click="edit(data.id)"
ontouchstart="touchStart()" ontouchend="touchEnd()"
ontouchmove="touchMove()">
<p ng-class="deleteMode ? 'note-list-title w-80' : 'note-list-title'"
ng-bind-html="data.title"></p>
<p ng-class="deleteMode ? 'note-list-date w-80' : 'note-list-date'">{{data.dateCreated | displayDate}}</p>
<div ng-if="deleteMode" class="note-list-delete ease-in" ng-click="delete($event, data.id)">
<span class="btn fa fa-trash"></span>
</div>
</div>
<div ng-if="!deleteMode" ng-click="new()" class="add-btn btn btn-primary ease-in">
<span class="fa fa-plus"></span>
</div>
</div>
<div ng-if="!showList" class="ease-in">
<div>
<div ng-click="back()" class="btn btn-primary"><span class="fa fa-arrow-left"></span></div>
<div ng-disabled="!isDataChanged" ng-click="save()" class="btn btn-primary" style="float:right">
<span class="fa fa-check"></span>
</div>
</div>
<div contenteditable="true" class="note-title"
ng-bind-html="selected.title" id="title">
</div>
<div contenteditable="true" class="note-container" ng-bind-html="selected.note" id="note"></div>
</div>
</div>
<script src="../js/pages/note.js"></script>
Calling it from:
$scope.loadViewModels($scope.orderBy, 'notes');
The sqlite query:
query: function (query, cb) {
db.transaction(function (tx) {
tx.executeSql(query, [], function (tx, res) {
return cb(res.rows, null);
});
}, function (error) {
return cb(null, error.message);
}, function () {
//console.log('query ok');
});
},
It is apache cordova framework, so it uses webview in Android emulator.
My Code Structure
<html ng-app="app" ng-controller="pageController">
<head>....</head>
<body>
....
<div id="pageContent" class="root-page" ng-controller="noteController" ng-cloak>
....
</div>
</body>
</html>
So there is controller inside controller. The parent is pageController and the child is noteController. Is a structure like this slowing the ng-repeat directives?
Btw using track by is not helping. There is still delay when rendering it. Also I can modify the entries as well, so when an entry was updated, it should be updated in the list as well.
NOTE
After thorough investigation there is something weird. Usually ng-repeat item has hash key in it. In my case ng-repeat items do not have it. Is it the cause of the problem?
One approach to improve performance is to use the track by clause in the ng-repeat expression:
<div class="list" ng-repeat="entry in data track by entry.id">
<h3>{{entry.title}}</h3>
</div>
From the Docs:
Best Practice: If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance, e.g. item in items track by item.id. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance.
For more information, see
AngularJS ngRepeat API Reference -- Tracking and Duplicates
In your html, try this:
<div class="list" ng-repeat="entry in data">
<h3 ng-bind="entry.title"></h3>
</div>
After thorough research, I found my problem. Every time I reset / reload my $scope.viewModels I always assign it to null / empty array first. This what causes the render delay.
Example:
$scope.search = function (table) {
$scope.currentPage = 1;
$scope.endOfPage = false;
$scope.viewModels = []; <------ THIS
$scope.loadViewModels($scope.orderBy, table);
}
So instead of assigning it to null / empty array, I just replace it with the new loaded data, and the flickering is gone.
I have this Orders array and on the inner div order, I check which status it has.
<div class="list-group" v-for="(order, key) in orders">
<div class="order" v-if="checkOrderStatus(order.status)">
<div class="dishes">
<ul id="dishes" v-for="dish in order.dishes" >
<li v-if="checkDishOnOrder(dish)">{{checkDishOnOrder(dish).quantity}} x {{checkDishOnOrder(dish).dishName}}</li>
</ul>
</div>
<div class="notInclude">
<ul id="notInclude" v-for="dish in order.dishes" >
<li v-if="checkForNotInclude(dish)">{{checkForNotInclude(dish)}}</li>
</ul>
</div>
<div class="table">
<center><span id="table">{{order.tableID}}</span></center>
</div>
<div class="hour">
<center><span id="hour">{{order.hour}}</span></center>
</div>
<div class="status">
<center><button type="button" id="status" :class="{'doingOrder' : order.status == 'Pedido pronto', 'orderDone' : order.status == 'Pronto para entrega'}" #click="changeStatus(order)">{{order.status}}</button></center>
</div>
</div>
</div>
On the beforeCreate: I binded this array with a firebase ref:
this.$bindAsArray('orders', database.ref('orders/' + user.uid).orderByChild('hourOrder'))
The problem is, every time I change a order status the last element of the array changes together and it should not happen.
Here is my checkOrderStatus: function:
checkOrderStatus: function(orderStatus) {
if(this.orderType == 'Em andamento') {
if(orderStatus != "Pronto para entrega") {
return true
}
} else if (this.orderType == 'Pedidos feitos') {
if(orderStatus == "Pronto para entrega") {
return true
}
}
},
Here is changeStatus: function:
changeStatus: function(order) {
var that = this;
var database = Firebase.database();
var loggedUser = Firebase.auth().currentUser;
if (order.status == 'Em andamento') {
order.status = 'Pedido pronto';
var orderKey = order['.key'];
delete order['.key'];
var updates = {};
updates['orders/' + loggedUser.uid + '/'+ orderKey] = order;
database.ref().update(updates).then(function() {
console.log('order Updated');
})
}
else if(order.status == 'Pedido pronto') {
order.status = 'Pronto para entrega';
var orderKey = order['.key'];
delete order['.key'];
var updates = {};
updates['orders/' + loggedUser.uid + '/'+ orderKey] = order;
database.ref().update(updates).then(function() {
console.log('order Updated');
})
}
},
I found a way to avoid this behavior using computed properties:
computed: {
fixedOrders() {
var database = Firebase.database();
this.$bindAsArray('orders', database.ref('orders/' + this.userID).orderByChild('hourOrder'))
return this.orders
},
}
I've binded the array again on a computed property, so that way it always have the right values for orders.
I'm just concerned about the performance loss because I'm biding the orders array again every time it changes.
Sorry if this is a really basic question but I'm in the process of learning Knockout and trying to wire up paging to my dataset.
In my code below, you will see that I am retrieving the dataset, and the page size dropdown affects the results appropriately. And when I change the page number (#'d links in footer of table), nothing happens. Could someone tell me what I'm missing?
function ViewModel(){
var vm = this;
// variables
vm.drinks = ko.observableArray();
vm.pageSizes = [15,25,35,50];
vm.pageSize = ko.observable(pageSizes[0]);
vm.currentPage = ko.observable(0);
// computed variables
// returns number of pages required for number of results selected
vm.PageCount = ko.computed(function(){
if(vm.pageSize()){
return Math.ceil(vm.drinks().length / vm.pageSize());
}else{
return 1;
}
});
// returns items from the array for the current page
vm.PagedResults = ko.computed(function(){
//return vm.drinks().slice(vm.currentPage, vm.pageSize());
return vm.drinks().slice(vm.currentPage() * vm.pageSize(), (vm.currentPage() * vm.pageSize()) + vm.pageSize());
});
// returns a list of numbers for all pages
vm.PageList = ko.computed(function(){
if(vm.PageCount() > 1){
return Array.apply(null, {length: vm.PageCount()}).map(Number.call, Number);
}
});
// methods
vm.ResetCurrentPage = function(){
vm.currentPage(0);
}
// go to page number
vm.GoToPage = function(page){
vm.currentPage(page);
}
// populate drink list
vm.GetDrinks = function(){
// get data
$(function () {
$.ajax({
type: "GET",
url: 'https://mysafeinfo.com/api/data?list=alcoholicbeverages&format=json',
dataType: "json",
success: function (data) {
vm.drinks(data);
}
});
});
}
// populate drinks
vm.GetDrinks();
}
// apply bindings
ko.applyBindings(ViewModel);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="row">
<div class="col-sm-3 pull-right form-horizontal">
<label class="control-label col-sm-4">
Results:
</label>
<div class="col-sm-8">
<select data-bind="value: pageSize,
optionsCaption: 'Page Size',
options: pageSizes, event:{ change: ResetCurrentPage }"
class="form-control"></select>
</div>
</div>
</div>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th style="width: 25%">Name</th>
<th>Category</th>
<th style="width: 50%">Description</th>
</tr>
</thead>
<tbody data-bind="foreach: PagedResults">
<tr>
<td data-bind="text: nm"></td>
<td data-bind="text: cat"></td>
<td data-bind="text: dsc"></td>
</tr>
</tbody>
<tfooter>
<tr>
<td colspan="3">
Current Page: <label data-bind="text: currentPage"></label><br />
<ul data-bind="foreach: PageList" class="pagination">
<li class="page-item"><a class="page-link" href="#" data-bind="text: $data + 1, click: GoToPage">1</a></li>
</ul>
</td>
</tr>
</tfooter>
</table>
Thanks to f_martinez for helping with my issue, here is the working example if anyone ends up here looking for how to do paging. jsfiddle
I will keep this open for now in case f_martinez would like to post an answer to accept.
function ViewModel() {
var vm = this;
// variables
vm.drinks = ko.observableArray();
vm.pageSizes = [15, 25, 35, 50];
vm.pageSize = ko.observable(pageSizes[0]);
vm.currentPage = ko.observable(0);
// computed variables
// returns number of pages required for number of results selected
vm.PageCount = ko.computed(function() {
if (vm.pageSize()) {
return Math.ceil(vm.drinks().length / vm.pageSize());
} else {
return 1;
}
});
// returns items from the array for the current page
vm.PagedResults = ko.computed(function() {
if (vm.PageCount() > 1) {
//return vm.drinks().slice(vm.currentPage, vm.pageSize());
return vm.drinks().slice(vm.currentPage() * vm.pageSize(), (vm.currentPage() * vm.pageSize()) + vm.pageSize());
} else {
return vm.drinks();
}
});
// returns a list of numbers for all pages
vm.PageList = ko.computed(function() {
if (vm.PageCount() > 1) {
return Array.apply(null, {
length: vm.PageCount()
}).map(Number.call, Number);
}
});
// methods
// reset to first page
vm.ResetCurrentPage = function() {
vm.currentPage(0);
}
// go to page number
vm.GoToPage = function(page) {
vm.currentPage(page);
}
// determines if page # is active returns active class
vm.GetClass = function(page) {
return (page == vm.currentPage()) ? "active" : "";
}
// populate drink list
vm.GetDrinks = function() {
// get data
$(function() {
$.ajax({
type: "GET",
url: 'https://mysafeinfo.com/api/data?list=alcoholicbeverages&format=json',
dataType: "json",
success: function(data) {
vm.drinks(data);
}
});
});
}
// populate drinks
vm.GetDrinks();
}
// apply bindings
ko.applyBindings(ViewModel);
.pagination > li > a:focus,
.pagination > li > a:hover,
.pagination > li > span:focus,
.page-link.active {
background-color: rgb(238, 238, 238);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="row">
<div class="col-sm-3 pull-right form-horizontal">
<label class="control-label col-sm-4">
Results:
</label>
<div class="col-sm-8">
<select data-bind="value: pageSize,
optionsCaption: 'All Results',
options: pageSizes, event:{ change: ResetCurrentPage }" class="form-control"></select>
</div>
</div>
</div>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th style="width: 25%">Name</th>
<th>Category</th>
<th style="width: 50%">Description</th>
</tr>
</thead>
<tbody data-bind="foreach: PagedResults">
<tr>
<td data-bind="text: nm"></td>
<td data-bind="text: cat"></td>
<td data-bind="text: dsc"></td>
</tr>
</tbody>
<tfooter>
<tr>
<td colspan="3" class="text-center">
<ul data-bind="foreach: PageList" class="pagination">
<li class="page-item">
</li>
</ul>
</td>
</tr>
</tfooter>
</table>
Stack overflow is about giving solution to common problems, and the answer solution is valid for OP ,but it is not very re-usable for other cases, Here is re-usable solution to this common problem (Knockout paging)
I am working on website, which has a lot of tables (most of them need paging), so actually I needed some reusable-component for paging to use it in all the cases which I need paging.
So I developed my own component of the this issue, here it is.
Now on Github
JsFiddle
And for more details, continue reading
JavaScript
function PagingVM(options) {
var self = this;
self.PageSize = ko.observable(options.pageSize);
self.CurrentPage = ko.observable(1);
self.TotalCount = ko.observable(options.totalCount);
self.PageCount = ko.pureComputed(function () {
return Math.ceil(self.TotalCount() / self.PageSize());
});
self.SetCurrentPage = function (page) {
if (page < self.FirstPage)
page = self.FirstPage;
if (page > self.LastPage())
page = self.LastPage();
self.CurrentPage(page);
};
self.FirstPage = 1;
self.LastPage = ko.pureComputed(function () {
return self.PageCount();
});
self.NextPage = ko.pureComputed(function () {
var next = self.CurrentPage() + 1;
if (next > self.LastPage())
return null;
return next;
});
self.PreviousPage = ko.pureComputed(function () {
var previous = self.CurrentPage() - 1;
if (previous < self.FirstPage)
return null;
return previous;
});
self.NeedPaging = ko.pureComputed(function () {
return self.PageCount() > 1;
});
self.NextPageActive = ko.pureComputed(function () {
return self.NextPage() != null;
});
self.PreviousPageActive = ko.pureComputed(function () {
return self.PreviousPage() != null;
});
self.LastPageActive = ko.pureComputed(function () {
return (self.LastPage() != self.CurrentPage());
});
self.FirstPageActive = ko.pureComputed(function () {
return (self.FirstPage != self.CurrentPage());
});
// this should be odd number always
var maxPageCount = 7;
self.generateAllPages = function () {
var pages = [];
for (var i = self.FirstPage; i <= self.LastPage() ; i++)
pages.push(i);
return pages;
};
self.generateMaxPage = function () {
var current = self.CurrentPage();
var pageCount = self.PageCount();
var first = self.FirstPage;
var upperLimit = current + parseInt((maxPageCount - 1) / 2);
var downLimit = current - parseInt((maxPageCount - 1) / 2);
while (upperLimit > pageCount) {
upperLimit--;
if (downLimit > first)
downLimit--;
}
while (downLimit < first) {
downLimit++;
if (upperLimit < pageCount)
upperLimit++;
}
var pages = [];
for (var i = downLimit; i <= upperLimit; i++) {
pages.push(i);
}
return pages;
};
self.GetPages = ko.pureComputed(function () {
self.CurrentPage();
self.TotalCount();
if (self.PageCount() <= maxPageCount) {
return ko.observableArray(self.generateAllPages());
} else {
return ko.observableArray(self.generateMaxPage());
}
});
self.Update = function (e) {
self.TotalCount(e.TotalCount);
self.PageSize(e.PageSize);
self.SetCurrentPage(e.CurrentPage);
};
self.GoToPage = function (page) {
if (page >= self.FirstPage && page <= self.LastPage())
self.SetCurrentPage(page);
}
self.GoToFirst = function () {
self.SetCurrentPage(self.FirstPage);
};
self.GoToPrevious = function () {
var previous = self.PreviousPage();
if (previous != null)
self.SetCurrentPage(previous);
};
self.GoToNext = function () {
var next = self.NextPage();
if (next != null)
self.SetCurrentPage(next);
};
self.GoToLast = function () {
self.SetCurrentPage(self.LastPage());
};
}
HTML
<ul data-bind="visible: NeedPaging" class="pagination pagination-sm">
<li data-bind="css: { disabled: !FirstPageActive() }">
<a data-bind="click: GoToFirst">First</a>
</li>
<li data-bind="css: { disabled: !PreviousPageActive() }">
<a data-bind="click: GoToPrevious">Previous</a>
</li>
<!-- ko foreach: GetPages() -->
<li data-bind="css: { active: $parent.CurrentPage() === $data }">
<a data-bind="click: $parent.GoToPage, text: $data"></a>
</li>
<!-- /ko -->
<li data-bind="css: { disabled: !NextPageActive() }">
<a data-bind="click: GoToNext">Next</a>
</li>
<li data-bind="css: { disabled: !LastPageActive() }">
<a data-bind="click: GoToLast">Last</a>
</li>
</ul>
Features
Show on need When there is no need for paging at all (for example the items which need to display less than the page size) then the HTML component will disappear.
This will be established by statement data-bind="visible: NeedPaging".
Disable on need
for example, if you are already selected the last page, why the last page or the Next button should be available to press?
I am handling this and in that case I am disabling those buttons by applying the following binding data-bind="css: { disabled: !PreviousPageActive() }"
Distinguish the Selected page
a special class (in this case called active class) is applied on the selected page, to make the user know in which page he/she is right now. This is established by the binding data-bind="css: { active: $parent.CurrentPage() === $data }"
Last & First
going to the first and last page is also available by simple buttons dedicated to this.
Limits for displayed buttons
suppose you have a lot of pages, for example 1000 pages, then what will happened? would you display them all for the user ? absolutely not you have to display just a few of them according to the current page. for example showing 3 pages before the page page and other 3 pages after the selected page.
This case has been handled here <!-- ko foreach: GetPages() -->
the GetPages function applying a simple algorithm to determine if we need to show all the pages (the page count is under the threshold, which could be determined easily), or to show just some of the buttons.
you can determine the threshold by changing the value of the maxPageCount variable
Right now I assigned it as the following var maxPageCount = 7; which mean that no more than 7 buttons could be displayed for the user (3 before the SelectedPage, and 3 after the Selected Page) and the Selected Page itself.
You may wonder, what if there was not enough pages after OR before the current page to display? do not worry I am handling this in the algorithm for example, if you have 11 pages and you have maxPageCount = 7 and the current selected page is 10, Then the following pages will be shown
5,6,7,8,9,10(selected page),11
so we always stratifying the maxPageCount, in the previous example showing 5 pages before the selected page and just 1 page after the selected page.
Selected Page Validation
All set operation for the CurrentPage observable which determine the selected page by the user, is go through the function SetCurrentPage. In only this function we set this observable, and as you can see from the code, before setting the value we make validation operations to make sure that we will not go beyond the available page of the pages.
Already clean
I use only pureComputed not computed properties, which means you do not need to bother yourself with cleaning and disposing those properties. Although ,as you will see in example below, you need to dispose some other subscriptions which are outside of the component itself
NOTE 1
You may noticed that I am using some bootstrap classes in this component,
This is suitable for me, but of course you can use your own classes instead of the bootstrap classes.
The bootstrap classes which I used here are pagination, pagination-sm, active and disabled
Feel free to change them as you need.
NOTE 2
So I introduced the component for you, It is time to see how it could work.
You would integrate this component in your main ViewModel as like this.
function MainVM() {
var self = this;
self.PagingComponent = ko.observable(new Paging({
pageSize: 10, // how many items you would show in one page
totalCount: 100, // how many ALL the items do you have.
}));
self.currentPageSubscription = self.PagingComponent().CurrentPage.subscribe(function (newPage) {
// here is the code which will be executed when the user change the page.
// you can handle this in the way you need.
// for example, in my case, I am requesting the data from the server again by making an ajax request
// and then updating the component
var data = /*bring data from server , for example*/
self.PagingComponent().Update({
// we need to set this again, why? because we could apply some other search criteria in the bringing data from the server,
// so the total count of all the items could change, and this will affect the paging
TotalCount: data.TotalCount,
// in most cases we will not change the PageSize after we bring data from the server
// but the component allow us to do that.
PageSize: self.PagingComponent().PageSize(),
// use this statement for now as it is, or you have to made some modifications on the 'Update' function.
CurrentPage: self.PagingComponent().CurrentPage(),
});
});
self.dispose = function () {
// you need to dispose the manual created subscription, you have created before.
self.currentPageSubscription.dispose();
}
}
Last but not least, Sure do not forget to change the binding in the html component according to you special viewModel, or wrap all the component with the with binding like this
<div data-bind="with: PagingComponent()">
<!-- put the component here -->
</div>
Cheers
I am trying to create a switch based on a dynamic array of objects...
For example:
<div ng-switch on="currentItem">
<div ng-repeat="item in myItems" ng-switch-when="item.name">
<p>{{item.name}}</p>
<button ng-click="nextItem(item)">Next Item</button>
</div>
</div>
And then in my controller...
$scope.myItems = [{
"name": "one"
}, {
"name": "two"
}]
// Default first item
$scope.currentItem = $scope.myItems[0].name;
$scope.nextItem = function(med) {
for (var i = 0; i < $scope.myItems.length; i++) {
if ($scope.currentItem === $scope.myItems[i].name) {
if ($scope.myItems[i + 1] !== undefined) {
$scope.currentItem = $scope.myItems[i + 1].name
}
}
}
}
Basically, the dom should render a div for each of the items, and when a user clicks the Next Item button, currentItem should be updated, and the switch should trigger based on that.
I am not seeing the first result as I should (nothing is being rendered). Any help would be greatly appreciated.
Plunk: http://plnkr.co/edit/PF9nncd1cJUNAjuAWK22?p=preview
I have forked your plunkr: http://plnkr.co/edit/A9BPFAVRSHuWlmbV7HtP?p=preview
Basically you where not using ngSwitch in a good way.
Just use ngIf:
<div ng-repeat="item in myItems">
<div ng-if="currentItem == item.name">
<p>{{item.name}}</p>
<button ng-click="nextItem(item)">Next Item</button>
</div>
</div>
I've forked your plunkr: http://plnkr.co/edit/2doEyvdiFrV74UXqAPZu?p=preview
Similar to Ignacio Villaverde, but I updated the way your getting the nextItem().
$scope.nextItem = function() {
var next = $scope.myItems[$scope.myItems.indexOf($scope.currentItem) + 1];
if(next) {
$scope.currentItem = next;
}
}
And you should probably keep a reference in currentItem to the entire object, not just the name:
<div ng-repeat="item in myItems">
<div ng-if="item == currentItem">
<p>{{item.name}}</p>
<button ng-click="nextItem(item)">Next Item</button>
</div>
Much simpler!