视图模型:
function Specialization(id, name) {
var self = this;
self.id = id;
self.name = name;
}
function ObservableSpecialization() {
var self = this;
self.availableItem = ko.observable();
}
function ViewModel() {
var self = this;
self.specializations = ko.observableArray([]);
self.availableSpecializations = [];
self.addSpecialization = function () {
self.specializations.push(new Specialization());
}
self.removeSpecialization = function (specialization) {
self.specializations.remove(specialization)
}
}
文件加载:
$(document).ready(function () {
var model = new ViewModel();
var temp = [];
$.each(window.availableSpecializations, function (i, item) {
var specialization = new Specialization(item.ID, item.Name);
model.availableSpecializations.push(specialization);
temp.push(item.ID);
});
$.each(window.userSpecializations, function (i, item) {
var idx = temp.indexOf(item.ID);
if (idx != -1) {
var available = model.availableSpecializations[idx];
var specialization = new ObservableSpecialization();
specialization.availableItem = available;
model.specializations.push(specialization);
}
});
ko.applyBindings(model);
});
<select>
摘录:
<tbody data-bind="foreach: specializations">
<tr>
<td>
<select name="Specializations" data-bind="options: $root.availableSpecializations, value: 'availableItem', optionsText: 'name'">
</select>
</td>
结果:
如下所示,所有值都始终设置为列表中的第一项..我猜ID不会以某种方式绑定到所选项目......我哪里出错?
答案 0 :(得分:2)
有两个问题:
首先,specialization.availableItem
是一个可观察的,因此应该分配一个函数调用:specialization.availableItem(available)
其次,在绑定字符串中,您有value: 'availableItem'
,它只是将select值设置为字符串'availableItem'。应该没有引号:value: availableItem
以下是2个修正案的小提琴:jsfiddle