我有以下场景,我使用ko.mapping从服务器获取一些数据并将其翻译成以下形式:
var viewModel = {
name: "Abc",
educations: [{ course: "C1", countryID: 1, cityID = 2},
{ course: "C2", countryID: 2, cityID = 3}]
}
我还有2个数组变量,它们是:
var countries = [{id=1,name="UAE"},{id=2,name="USA"},];
var cities = [{id=1,name="Dubai", cid=1},{id=2,name="Al-Ain", cid=1},
{id=3,name="Newyork", cid=2},{id=4,name="Houston", cid=2},];
现在显示/编辑此数据我有以下HTML
<div>
<input type="text" data-bind="value: Name"/>
<table data-bind="template: { name: 'cet', foreach: educations }">
</table>
</div>
<script type="text/html" id="cet">
<tr>
<td>
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Select...', value: countryID"></select>
</td>
<td>
<select data-bind="options: cities, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Select...', value: cityID"></select>
</td>
</tr>
</script>
现在我需要的是,当从服务器发送数据时,选择框应该显示与绑定对象相对应的正确项目。
答案 0 :(得分:0)
您已达到目标 - here是您的代码的有效版本。
var viewModel = {
name: "Abc",
educations: [{course: "C1", countryID: 1, cityID: 2},
{course: "C2", countryID: 2, cityID: 3}],
countries: [{id: 1, name: "UAE"}, {id: 2, name: "USA"}],
cities: [{id: 1, name: "Dubai", cid: 1},
{id: 2, name: "Al-Ain", cid: 1},
{id: 3, name: "Newyork", cid: 2},
{id: 4, name: "Houston", cid: 2}]
};
ko.applyBindings(viewModel);
<div>
<input type="text" data-bind="value: name" />
<table data-bind="template: { name: 'cet', foreach: educations }"></table>
</div>
<script type="text/html" id="cet">
<tr>
<td>
<select data-bind="options: $root.countries, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Select...', value: countryID"></select>
</td>
<td>
<select data-bind="options: $root.cities, optionsText: 'name', optionsValue: 'id', optionsCaption: 'Select...', value: cityID"></select>
</td>
</tr>
</script>
答案 1 :(得分:0)
好解决了:)
数据绑定应按如下方式进行:
<select id="Countries" name="Countries" data-bind="options: countries, optionsText: 'CountryName', optionsValue: 'CountryID', optionsCaption: 'Select...', value: SelectedCountryID"></select>
<select id="Cities" name="Cities" data-bind="options: Cities, optionsText: 'CityName', optionsValue: 'CityID', optionsCaption: 'Select...', value: CityID"></select>
首先,我必须运行 ko.mapping 将viewModel转换为&#34; Observable viewModel &#34;然后代码就像:
if(viewModel.educations() != undefined && viewModel.educations().length > 0) {
for(k in viewModel.educations()) {
var education = viewModel.educations()[k];
education.Cities = ko.observableArray();
education.SelectedCountryID = ko.computed({
read: function() {
return(this.CountryID());
},
write: function(value) {
this.CountryID(value);
this.Cities.removeAll();
if(value != undefined) {
for(c in cities) {
if(cities[c].cid == value) {
this.Cities.push(cities[c]);
}
}
}
},
owner: education,
});
if(viewModel.educations()[k].CountryID() != 0 ||
viewModel.educations()[k].CountryID() != undefined) {
viewModel.educations()[k].SelectedCountryID(viewModel.educations()[k].CountryID());
}
}
}