Knockout - Master details - hiding a combobox
http://stackoverflow.com/questions/11905827/knockout-adding-removing-select-dropdown-based-on-value-of-another-select-dropd
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.3.0.js"></script>
<div data-bind="visible: selectedItem() == null">
<table>
<tbody data-bind='foreach: items'>
<tr>
<td><span data-bind="text: name"/></td>
<td><button data-bind="click: $root.editItem">Edit</button></td>
</tr>
</tbody>
</table>
</div>
<hr />
<div data-bind="with: selectedItem">
<h4>Details for <span data-bind="text: name"></span>: </h4>
<table>
<thead>
<tr>
<th>Detail Name</th>
<th>Detail Type</th>
<th>Detail Subtype (Only for Type A)</th>
</tr>
</thead>
<tbody data-bind="foreach: itemDetails">
<tr>
<td><input type="text" data-bind="value: name"/>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
</td>
<td>
<select data-bind="options: $root.availableTypes, optionsText: 'name', optionsValue: 'id', value: type"></select>
</td>
<td data-bind="if: type() === 1">
<select data-bind="if: type() === 1, options: $root.availableSubtypes, optionsText: 'name', optionsValue: 'id', value: subtype"></select>
</td>
</tr>
</tbody>
</table>
<button data-bind="click: $root.addItemDetail">Add Detail</button>
<button data-bind="click: $root.cancelEdit">Cancel Edit</button>
</div>
CSS
table, th, td
{
border: 1px solid black;
}
JavaScript
var pm = pm || {};
pm.Item = function(name, itemDetails) {
var self = this;
self.name = ko.observable(name);
self.itemDetails = ko.observableArray();
for (var i = 0; i < itemDetails.length; i++) {
var detail = itemDetails[i];
self.itemDetails.push(new pm.ItemDetail(detail.type, detail.subtype));
}
return self;
};
pm.ItemDetail = function(type, subtype) {
var self = this;
self.type = ko.observable();
self.subtype = ko.observable();
//return self;
};
// View Model
pm.viewModel = function() {
var self = this,
items = ko.observableArray([]),
loadItems = function() {
items.push(new pm.Item('Item 1', [{
name: 'Item 1 Detail 1',
type: 1,
subtype: 1}]));
items.push(new pm.Item('Item 2', [{
name: 'Item 2 Detail 1',
type: 1,
subtype: 1}]));
},
availableTypes = [
{
name: 'Type A',
id: 1},
{
name: 'Type B',
id: 2},
],
availableSubtypes = [
{
name: 'Subtype A-1',
id: 1},
{
name: 'Subtype A-2',
id: 2},
],
selectedItem = ko.observable(),
editItem = function(item) {
selectedItem(item);
},
cancelEdit = function() {
selectedItem(null);
},
addItemDetail = function(item) {
// what should be here to add a new detail to an item?
selectedItem().itemDetails.push(new pm.ItemDetail());
};
return {
items: items,
loadItems: loadItems,
selectedItem: selectedItem,
editItem: editItem,
addItemDetail: addItemDetail,
cancelEdit: cancelEdit,
availableTypes: availableTypes,
availableSubtypes: availableSubtypes
...