KnockoutJS Paged Grid example with a pageSize drop-down - javascript

Working from the KO example found here: http://knockoutjs.com/examples/grid.html,
I want to add a drop-down to select different page sizes (e.g. 4, 8, 12 items per page) and update the page grid upon changing the drop-down.
tried a bunch of things and I know I am missing something to get this to work. Thanks in advance for any help or a link to an existing solution.
What I sort of have now:
=== View ===
<div data-bind='simpleGrid: gridViewModel'> </div>
<select class="form-control" name="displayCount" id="displayCount" data-bind="value: valueDisplayCount;">
<option value="4">4</option><option value="8">8</option><option value="16">16</option>
</select>
<button data-bind='click: addItem'>
Add item
</button>
<button data-bind='click: sortByName'>
Sort by name
</button>
<button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'>
Jump to first page
</button>
==== View Model =====
$( document ).ready(function(){
var initialData = [
{ name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
{ name: "Furious Lizard", sales: 152, price: 25.00 },
{ name: "Indifferent Monkey", sales: 1, price: 99.95 },
{ name: "Brooding Dragon", sales: 0, price: 6350 },
{ name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
{ name: "Optimistic Snail", sales: 420, price: 1.50 }
];
var PagedGridModel = function(items) {
this.items = ko.observableArray(items);
this.valueDisplayCount = ko.observable(4);
this.sortByName = function() {
this.items.sort(function(a, b) {
return a.name < b.name ? -1 : 1;
});
};
this.jumpToFirstPage = function() {
this.gridViewModel.currentPageIndex(0);
};
this.valUpdDisplayCount= function(){
alert($('#displayCount').val());
this.gridViewModel.pageSize(6);
};
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items,
columns: [
{ headerText: "Item Name", rowText: "name" },
{ headerText: "Sales Count", rowText: "sales" },
{ headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
],
pageSize: this.valueDisplayCount
});
};
ko.applyBindings(new PagedGridModel(initialData));
});
JSFiddle:
http://jsfiddle.net/RNunc/1/

You would need to tweak the simplegrid code to look for an observable for pageSize. The updates could look like:
ko.simpleGrid = {
// Defines a view model class you can use to populate a grid
viewModel: function (configuration) {
this.data = configuration.data;
this.currentPageIndex = ko.observable(0);
this.pageSize = configuration.pageSize || ko.observable(5);
// If you don't specify columns configuration, we'll use scaffolding
this.columns = configuration.columns || getColumnsForScaffolding(ko.unwrap(this.data));
this.itemsOnCurrentPage = ko.computed(function () {
var size = ko.unwrap(this.pageSize);
var startIndex = size * this.currentPageIndex();
return ko.unwrap(this.data).slice(startIndex, startIndex + size);
}, this);
this.maxPageIndex = ko.computed(function () {
return Math.ceil(ko.unwrap(this.data).length / ko.unwrap(this.pageSize)) - 1;
}, this);
}
};
The simplegrid code is here: http://knockoutjs.com/examples/resources/knockout.simpleGrid.3.0.js
http://jsfiddle.net/rniemeyer/82MAR/

Related

Copying data from a kendo treelist with keeping the table structure

I have an editable multi selectable kendo Treelist. I would like to be able to select part of the grid and copy paste its data in the same grid (other columns and rows) or to a text file. It is important to paste it with the same structure in the new table.
The copy feature is not supported for kendo Treelist.
Is there a way to do that with use of JavaScript and jQuery?
Kendo demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2023.1.117/styles/kendo.default-v2.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2023.1.117/js/kendo.all.min.js"></script>
</head>
<body>
<div id="treeList"></div>
<script>
$("#treeList").kendoTreeList({
columns: [
{ field: "name" },
{ field: "age" }
],
selectable: "multiple, cell",
editable:"incell",
dataSource: [
{ id: 1, parentId: null, name: "Jane Doe", age: 22 },
{ id: 2, parentId: 1, name: "John Doe", age: 24 },
{ id: 3, parentId: 1, name: "Jenny Doe", age: 3 }
]
});
</script>
</body>
</html>
I have used two buttons, one for copying and one for pasting. The events functions are as below. This solved my problem and I can also paste the copied text in excel.
<button onClick="copying()" >Copy</button>
<button onClick="pasting()" >Paste</button>
<div id="treeList"></div>
<script>
$("#treeList").kendoTreeList({
columns: [
{ field: "name" },
{ field: "age" }
],
selectable: "multiple, cell",
editable:"incell",
dataSource: [
{ id: 1, parentId: null, name: "Jane Doe", age: 22 },
{ id: 2, parentId: 1, name: "John Doe", age: 24 },
{ id: 3, parentId: 1, name: "Jenny Doe", age: 3 }
]
});
</script>
var copiedText="";
function copying(){
if(copiedText !== ""){
return;
}
var grid = $("#treeList").data("kendoTreeList");
var selected = grid.select();
var previousRowID = selected.eq(0).parent().index();
var isNewLine = true;
selected.each(function() {
var row = $(this).closest("tr");
var dataItem = grid.dataItem(this);
if (previousRowID !== $(this).parent().index()) {
copiedText += "\r\n";
isNewLine = true;
}
previousRowID = $(this).parent().index();
var colIndx = $("td", row).index(this);
var column = grid.columns[colIndx];
var data = dataItem;
var value = dataItem[column.field];
if (!isNewLine) {
copiedText += "\t";
}
copiedText += value;
isNewLine = false;
});
var textarea = $("<textarea>");
var offset = $(this).offset();
// Position the textarea on top of the Treelist and make it transparent.
textarea.css({
position: 'absolute',
opacity:0,
border: 'none',
width: $(this).find("table").width(),
height: $(this).find(".k-grid-content").height()
});
textarea.val(copiedText)
.appendTo('body')
.focus()
.select();
document.execCommand('copy');
setTimeout(function(){
textarea.remove();
});
}
function pasting() {
var pasteVal = copiedText;
var grid = $("#treeList").data("kendoTreeList");
if (pasteVal) {
var selectedArr= Object.values($(".k-grid td.k-selected"));
var pasteArray = pasteVal.split("\r\n").filter(r => r !== "").map(r => r.split("\t"));
pasteArray.forEach(function( item, index) {
selectedArr[index].innerHTML = item;
});
grid.refresh();
}
copiedText= "";
}

Knockout Table : Highlight a Table Row

I have an Example Fiddle here. In this Table I wish to achieve Highlighting a Particular Row selected. If unselected Row should not be highlighted.
One of many sample I found Fiddle but I am unable to incorporate them inside my Example Fiddle Above.
Below is the HTML Code which shows basic Table.
<table id="devtable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr data-bind=" click: $parent.select ">
<td data-bind="text: ID"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Status"></td>
</tr>
</tbody>
ID :
Name :
Status :
Here is the knockout function to do manipulations
<Script>
var rowModel = function (id, name, status) {
this.ID = ko.observable(id);
this.Name = ko.observable(name);
this.Status = ko.observable(status);
};
var myData = [{
id: "001",
name: "Jhon",
status: "Single"
}, {
id: "002",
name: "Mike",
status: "Married"
}, {
id: "003",
name: "Marrie",
status: "Complicated"
}];
function MyVM(data) {
var self = this;
self.items = ko.observableArray(data.map(function (i) {
return new rowModel(i.id, i.name, i.status);
}));
self.select = function(item) {
self.selected(item);
self.enableEdit(true);
};
self.flashCss = ko.computed(function () {
//just an example
return 'flash';
});
self.selected = ko.observable(self.items()[0]);
self.enableEdit = ko.observable(false);
self.changeTableData = function() {
// How do I change the Data here and it should also reflect on the Page.
// If I do binding depending on condition it gives me error
if(true){
var myData = [{
id: "001",
name: "Jhon",
status: "Single"
}, {
id: "002",
name: "Mike",
status: "Married"
}, {
id: "003",
name: "Marrie",
status: "Complicated"
}];
}
else{
myData = [{
id: "111",
name: "ABC",
status: "Single"
}, {
id: "222",
name: "XYZ",
status: "Married"
}, {
id: "3333",
name: "PQR",
status: "Complicated"
}];
}
}
}
ko.applyBindings(new MyVM(myData));
</script>
CSS code below
.flash { background-color: yellow; }
You can use the css binding to add the .flash class based on the currently selected value:
<tr data-bind="click: $parent.select,
css: { flash: $parent.selected() === $data }">
...
</tr>
If you don't like this logic being defined in the view, you can pass a reference to the selected observable and create a computed property inside your RowModel:
var RowModel = function( /* ... */ selectedRow) {
// ...
this.isSelected = ko.pureComputed(function() {
return selectedRow() === this;
}, this);
}
Here's the quick fix in your fiddle:
http://jsfiddle.net/wa78zoe4/
P.S. if you want toggle-behavior, update select to:
self.select = function(item) {
if (item === self.selected()) {
self.selected(null);
self.enableEdit(false);
} else {
self.selected(item);
self.enableEdit(true);
}
};

Pagination with filters using ng-repeat in angular

I am trying to do a pagination using filters.
There is a list with names and countries.
I am trying to filter them by country and also alphabetical range, and then generate the pagination by numbers. I am really stuck with it. any help will be really appreciate it
The alphabetical filter will retrieve the names that start with the the range of letters. For example if you select the first option [A - M] will return the person that their name start within that range of letters
Here is my code. The html is over there. Thanks
http://jsbin.com/cifowatuzu/edit?html,js,output
angular.module('app',['angular.filter'])
.controller('MainController', function($scope) {
$scope.selectedCountry = '';
$scope.currentPage = 1;
$scope.pageSize = 3;
$scope.pages = [];
//This should store {StartFrom and To from selected Range}
$scope.selectedRange = '';
$scope.AlphabethicalRange = [
{StartFrom: 'A', To: 'M'},
{StartFrom: 'N', To: 'Z'}
];
$scope.Countries = [
{ Name : 'USA'},
{ Name : 'Japan'},
{ Name : 'France'},
{ Name : 'Canada'},
{ Name : 'China'},
];
$scope.People = [
{ Id: 1, Name: 'Will', Country: 'USA'},
{ Id: 2, Name: 'Ed', Country: 'USA' },
{ Id: 3, Name: 'Peter', Country: 'China'},
{ Id: 4, Name: 'John', Country: 'Japan'},
{ Id: 5, Name: 'Alex', Country: 'France'},
{ Id: 6, Name: 'Jim', Country: 'France'},
{ Id: 7, Name: 'Austin', Country: 'Italy'},
{ Id: 8, Name: 'Men', Country: 'France'},
{ Id: 9, Name: 'Zike', Country: 'Canada'},
];
$scope.numberPages = Math.ceil($scope.People.length / $scope.pageSize);
$scope.init = function () {
for (i = 1; i < $scope.numberPages; i++) {
$scope.pages.push(i);
}
};
$scope.init();
});
I create a custom filter to filter the range that you want.
Here's a snippet working:
var app = angular.module('app', ['angular.filter']);
app.controller('mainCtrl', function ($scope) {
$scope.currentPage = 1;
$scope.pageSize = 3;
$scope.pages = [];
$scope.AlphabethicalRange = [
{
"StartFrom":"A",
"To":"M"
},
{
"StartFrom":"N",
"To":"Z"
}
];
$scope.Countries = [
{
"Name":"USA"
},
{
"Name":"Japan"
},
{
"Name":"France"
},
{
"Name":"Canada"
},
{
"Name":"China"
}
];
$scope.People = [
{
"Id":1,
"Name":"Will",
"Country":"USA"
},
{
"Id":2,
"Name":"Ed",
"Country":"USA"
},
{
"Id":3,
"Name":"Peter",
"Country":"China"
},
{
"Id":4,
"Name":"John",
"Country":"Japan"
},
{
"Id":5,
"Name":"Alex",
"Country":"France"
},
{
"Id":6,
"Name":"Jim",
"Country":"France"
},
{
"Id":7,
"Name":"Austin",
"Country":"Italy"
},
{
"Id":8,
"Name":"Men",
"Country":"France"
},
{
"Id":9,
"Name":"Zike",
"Country":"Canada"
}
];
$scope.numberPages = Math.ceil($scope.People.length / $scope.pageSize);
$scope.init = function() {
for (i = 1; i < $scope.numberPages; i++) {
$scope.pages.push(i);
}
};
$scope.init();
});
app.filter('rangeAlphaFilter', function() {
return function(items, search) {
if (!search || search == ' - ') {
return items;
}
return items.filter(function(element) {
return new RegExp('[' + search.replace(/ /g, '') + ']', 'i').test(element.Name[0]);
});
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div>
<span>Country Filter</span>
<select name="countriesSelect" ng-options="c as c.Name for c in Countries" ng-model="selectedCountry">
<option value="">-- Select a country --</option>
</select>
<br>
<span>Alphabetical Filter</span>
<select name="AlphabeticalSelect" ng-options="a as a.StartFrom +' - '+ a.To for a in AlphabethicalRange" ng-model="selectedRange">
<option value="">-- Select a range --</option>
</select>
<ul>
<li ng-repeat="person in People | filter: { Country: selectedCountry.Name } | rangeAlphaFilter: selectedRange.StartFrom +' - '+ selectedRange.To" ng-bind="person.Name"></li>
</ul>
<span>Pagination Numbers</span>
{{page}}
</div>
</body>
</html>
PS: To control the pagination, I extremely don't recommend you to do it manually, it gives a lot of work. I recommend you to see my answer in this another question, it's like a "mini" tutorial of how to use the angularUtils-pagination. Check it.
I hope it helps.

AngularJS input.radio initial selection

I'm trying to initialise/select a particular radio button within a group. I want to pass in an index number to an attribute called "selected-item".
HTML
<div class="top">
<radio-buttons model="colour" selected-item="1" items='colours'></radio-buttons>
<div>{{colour}}</div>
</div>
<div class="center">
<radio-buttons model="day" selected-item="2" items='days'></radio-buttons>
<div>{{day}}</div>
</div>
<div class="bottom">
<radio-buttons model="phone" selected-item="3" items="phones"></radio-buttons>
<div>{{phone}}</div>
</div>
Directive:
directives.directive('radioButtons', function () {
return {
restrict: 'E',
scope: {
model: '=',
items: '=',
selectedItem: '#'
},
templateUrl: 'template/radio-group.html',
link: function(scope) {
console.log(scope.selectedItem);
scope.onItemChange = function(item) {
console.log(item);
scope.model = item;
};
}
};
});
Template: radio-group.html:
<div ng-repeat='item in items'>
<input
type="radio"
name="{{item.group}}"
ng-value="{{item.value}}"
ng-model="model"
ng-change="onItemChange(item)"/>
{{item.text}}
</div>
Controller
$scope.colours= [ {
text: "Pink",
value: 5,
group: "colourGroup",
img: 'app/img/icon.jpg'
}, {
text: "Yellow",
value: 6,
group: "colourGroup",
img: 'app/img/icon.jpg'
}, {
text: "Blue",
value: 7,
group: "colourGroup",
img: 'app/img/icon.jpg'
}, {
text: "Green",
value: 8,
group: "colourGroup",
img: 'app/img/icon.jpg'
}
];
$scope.days = [ {
text: "Monday",
value: 9,
group: "dayGroup"
}, {
text: "Tuesday",
value: 10,
group: "dayGroup"
}, {
text: "Wednesday",
value: 11,
group: "dayGroup"
}, {
text: "Thursday",
value: 12,
group: "dayGroup"
}
];
$scope.phones = [ {
text: "Android",
group: "phoneGroup",
value: 13
}, {
text: "iOS",
group: "phoneGroup",
value: 14
}, {
text: "Blackberry",
group: "phoneGroup",
value: 15
}];
Any help would be fantastic!
Cheers.
Try changing ng-value="{{item.value}}" to value="{{item.value}}".
Then add ng-checked="$index == (selectedItem - 1)" to the input in the template.
Alternatively: ng-checked="$index == (selectedItem - 1) || $first" or with $last, if you want it to select something if you try an index that is out of range.
Without using value, here is another solution:
link: function(scope) {
scope.model = angular.copy(scope.items[scope.selectedItem -1]);
var setSelected = function(v) {
var i = 0;
for(; i < scope.items.length;i++) {
if(scope.items[i].value === v) {
return scope.items[i];
}
}
}
scope.$watch('model.value',function(v) {
//because the value is out of sync with the model, have to reset the model
scope.model = angular.copy(setSelected(v));
});
}
Note that ng-value has to be a string, and therefore ng-model. scope.model is only exposed as scope in your directive, so am using scope.model.value
<div ng-repeat='item in items'>
<input
type="radio"
name="{{item.group}}"
ng-value="{{item.value}}"
ng-model="model.value" />
{{item.text}}
</div>

Nested menu using parent id in knockoutJs

I am try to create nested menu using given json data by the client.
Data :
var serverData = [
{
Id: "menuColorSearch",
Text: "Color search"
},
{
Id: "menuAncillaryProductMix",
Text: "Ancillary product mix"
},
{
Id: "menuDocuments",
Text: "Documents"
},
{
Id: "menuColorInfo",
ParentId: "menuDocuments",
Text: "Color info"
},
{
Id: "menuReports",
ParentId: "menuDocuments",
Text: "Reports"
},
{
Id: "menuMaintenance",
Text: "Maintenance"
},
{
Id: "menuPriceManagement",
ParentId: "menuMaintenance",
Text: "Price management"
}
];
I am trying like this :
var Menu = function(dept, all) {
var self = this;
this.id = dept.Id;
this.name = ko.observable(dept.Text);
this.parentId = dept.ParentId;
this.children = ko.observableArray();
ko.utils.arrayForEach(all || [], function(menu) {
if(menu.ParentId){
if (menu.ParentId === self.id) {
self.children.push(new Menu(menu, all));
}
}else{
new Menu(menu, all)
}
});
};
var ViewModel = function(data) {
this.root = new Menu(data[0], data);
};
$(function() {
ko.applyBindings(new ViewModel(serverData));
});
Templates :
<div data-bind="with: root">
<ul data-bind="template: 'deptTmpl'">
</ul>
</div>
<script id="deptTmpl" type="text/html">
<li>
<a data-bind="text: name"></a>
<ul data-bind="template: { name: 'deptTmpl', foreach: children }">
</ul>
</li>
</script>
problem is that its only work when 2nd and 3rd object has parent ID. i am trying something like it should make nested menu according to given json data. so id there is no parent id on object it should add on root. and if object has parent id it should add according to parent id.
Please help me to correct my code or guide me if these is another way to do this in KnockoutJS.
Thanks
This should help you http://jsfiddle.net/MCNK8/3/, the main idea is to rebuild main data array, by placing child inside parent
HTML
<script id="nodeTempl" type="text/html">
<li>
<a data-bind="text: Text"></a>
<ul data-bind="template: {name: nodeTemplate, foreach: children }"></ul>
</li>
</script>
<script id="nodeLeafTempl" type="text/html">
<li>
<a data-bind="text: Text"></a>
</li>
</script>
<ul data-bind="template: {name: nodeTemplate, foreach: children }"></ul>
Javascript (#see fiddle)
var serverData = [
{
Id: "menuColorSearch",
Text: "Color search"
},
{
Id: "menuAncillaryProductMix",
ParentId: 'menuColorSearch',
Text: "Ancillary product mix"
},
{
Id: "menuDocuments",
Text: "Documents"
},
{
Id: "menuColorInfo",
ParentId: "menuReports",
Text: "Color info"
},
{
Id: "menuReports",
ParentId: "menuDocuments",
Text: "Reports"
},
{
Id: "menuMaintenance",
ParentId: 'menuReports',
Text: "Maintenance"
},
{
Id: "menuPriceManagement",
ParentId: "menuMaintenance",
Text: "Price management"
}
];
function getNestedMenu(index, all) {
var root = all[index];
if(!root){
return all;
}
if(!all[index].children){
all[index].children = [];
}
for(var i = 0; i < all.length; i++){
//<infinity nesting?>
//put children inside it's parent
if(all[index].Id == all[i].ParentId){
all[index].children.push(all[i]);
all[i].used = true;
}
//this is needed for each item, to determine which template to use
all[index].nodeTemplate = function(node) {
return node.children.length > 0 ? 'nodeTempl' : 'nodeLeafTempl';
}
//</infinity nesting?>
}
return getNestedMenu(++index, all);
};
function getModel(data) {
var items = getNestedMenu(0, data);
//<remove duplicates, for infinity nesting only>
for(var i = 0; i < items.length; i++){
if(items[i].used){
items.splice(i, 1);
i--;
}
}
//</remove duplicates, for infinity nesting only>
//<build root item>
var model = {};
model.children = ko.observableArray(items);
model.nodeTemplate = function(node) {
return node.children.length > 0 ? 'nodeTempl' : 'nodeLeafTempl';
}
//</build root item>
console.log(items);
return model;
};
(function() {
//new ViewModel(serverData);
ko.applyBindings(getModel(serverData));
})();

Categories