Reputation: 699
I am creating a dynamic table say having column A,B,C and populating it with data, I also have 1 listbox where I have A,B,C as checkbox so based on the selected checkbox I am displaying the columns e.g. I have selected B,C from listbox then I can creating the table only for B,C and not A, creating jquery template for this scenario and data bind using Knockout.js is what I m looking for, but I doubt whether templates can be used in this scenario as my table is too dynamic..so my question is whether it is possible to use knockout in this scenario. If no then my approach of using plain jquery will be the right option.
if I am following jquery approach my idea of separating the View and ViewModel will be an issue as in this case View Model will have jquery related view operations
any samples on this will be highly useful.
Thanks and Regards, Sajesh Nambiar
Upvotes: 3
Views: 11121
Reputation: 8510
You can easily hide/display table columns using knockout. An simple, but effective, way is to use the visible
binding on the column to control its visibility.
Here's a fiddle that demonstrates the idea: http://jsfiddle.net/Ex9J9/42/
Edit - updated fiddle to fix 404 error with Knockout resource
view:
<h4>Select Columns:</h4>
<ul data-bind="foreach: gridOptions.columns">
<li>
<label>
<input type="checkbox" data-bind="checked: isVisible" /> <span data-bind="text: header"></span>
</label>
</li>
</ul>
<hr>
<table>
<thead>
<tr data-bind="foreach: gridOptions.columns">
<th data-bind="visible:isVisible, text: header"></th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr data-bind="foreach: $parent.gridOptions.columns">
<td data-bind="text: $parent[dataMember], visible:isVisible"></td>
</tr>
</tbody>
</table>
view model:
var vm = {
gridOptions: {
columns: [{
header: 'First Name',
dataMember: 'firstName',
isVisible: ko.observable(true)
}, {
header: 'Last Name',
dataMember: 'lastName',
isVisible: ko.observable(true)
}]
},
people: [{
firstName: 'Bert',
lastName: 'Bertington'
}, {
firstName: 'Charles',
lastName: 'Charlesforth'
}, {
firstName: 'Denise',
lastName: 'Dentiste'
}]
};
ko.applyBindings(vm);
Upvotes: 10
Reputation: 1228
If the options are small like 3 or so you can create three templates and then in the page do something like this:
<!-- ko 'if': AIsSelectedAndNotBOrC == true -->
//display the tmeplate
<!-- /ko -->
// Do this for your other variations...
This will work but if you have many variations then it could be too cumbersome.
Upvotes: 0