视图模型:
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 没有以某种方式绑定到选定的项目...我哪里出错了?