问题
I'm trying to do a simple cascading combobox using knockoutjs. My first combobox binds to 2 properties in the viewmodel:
BusinessLines as the source for comboboxoptions
SelectedBusinessLine as the selected item in the first combobox.
Each BusinessLine has a collection of Clusters.
The second combox should data bind to the SelectedBusinessLine.Clusters observable for combobox options source, and SelectedCluster for the selected option.
The problems is that the second combobox doesn't get populated at all.
Source in JsFiddle (In JsFiddle the first binding doesn't work either, sry firs time use)
JavaScript
var mainViewModel = null;
$(document).ready(function() {
var mainViewModelData = <%= JsonConvert.SerializeObject(NewRequestViewModel) %>;
mainViewModel = ko.mapping.fromJS(mainViewModelData);
ko.applyBindings(mainViewModel);
});
HTML
<div>
<table>
<tr>
<td>
Business Line
</td>
<td>
<select data-bind="options: BusinessLines,
optionsText: 'Title',
value: SelectedBusinessLine,
optionsCaption: 'Select Business Line..'">
</select>
</td>
</tr>
<tr>
<td>
Cluster
</td>
<td>
<select data-bind="options: SelectedBusinessLine.Clusters,
optionsText: 'Title',
value: SelectedCluster,
optionsCaption: 'Select Cluster..'">
</select>
</td>
</tr>
</table>
</div>
Update:
Second solution (without computed props)
<select data-bind="options: SelectedBusinessLine() ? SelectedBusinessLine().Clusters() : [],
optionsText: 'Title',
value: SelectedCluster,
optionsCaption: 'Select Cluster..'">
</select>
回答1:
Here is a working version:
http://jsfiddle.net/x2qMg/4/
Your fiddle wasn't working (at all) because you did not include the Knockout Mapping JS reference (the mapping plugin in not part of the main Knockout JS) - see the Manage Resources area in the left side bar.
You'll see the biggest change I made was to use a with
binding to only render Clusters when a Business Line has been selected. Also note that I had to use $root.SelectedCluster as otherwise it would not be found within the Selected Business Line context created by the with
.
来源:https://stackoverflow.com/questions/11386624/knockoutjs-simple-cascading-selects