这是我的View模型,它有助于加载要下拉的项目。项目正在加载,但是当我检查元素"值"属性为空。我怎样才能获得选定的价值?
$(function () {
tss.Department = function (selectedItem) {
var self = this;
self.id = ko.observable();
self.description = ko.observable();
self.isSelected = ko.computed(function () {
return selectedItem() === self;
});
self.stateHasChanged = ko.observable(false);
};
tss.vm = (function () {
var metadata = {
pageTitle: "My App"
},
selectedDepartment = ko.observable(),
departments = ko.observableArray([]),
sortFunction = function (a, b) {
return a.description().toLowerCase() > b.description().toLowerCase() ? 1 : -1;
},
selectDepartment = function (p) {
selectedDepartment(p);
},
loadDepartments = function () {
tss.departmentDataService.getDepartments(tss.vm.loadDepartmentsCallback);
},
loadDepartmentsCallback = function (json) {
$.each(json, function (i, p) {
departments.push(new tss.Department(selectedDepartment)
.id(p.DepartmentId)
.description(p.Description)
);
});
departments.sort(sortFunction);
};
return {
metadata: metadata,
departments: departments,
selectDepartment: selectDepartment,
loadDepartmentsCallback: loadDepartmentsCallback,
loadDepartments: loadDepartments,
choices: choices,
selectedChoice: selectedChoice
};
})();
tss.vm.loadDepartments();
ko.applyBindings(tss.vm);
});
这是我的HTML
<select data-bind="options:departments, value:selectDepartment,
optionsText: 'description', optionsCaption:'Select a product ...'">
</select>
也没有进行排序。 departmentDataService用于调用外部数据。它有&#34; id&#34;和&#34;描述&#34;
我也尝试将值设置为&#39; Id&#39;,但无法正常工作。
答案 0 :(得分:1)
您不应该使用附加函数selectDepartment
将值传递给observable,而是直接将observable绑定到select-box的value属性:
<select data-bind="options:departments, value:selectedDepartment, ...
(记得导出selectedDepartment
可观察的)
value属性不仅用于将当前值从视图传递到viewmodel,反之亦然:设置所选选项。因此,绑定到仅提供“写入”功能的函数是不够的。
如果您需要对所选部门的更改作出反应,您可以订阅observable(这在官方文档中有解释)。