这是我的 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用于调用外部数据。它同时具有“id”和“description”
我也尝试将值设置为“Id”,但没有成功。
最佳答案
您不应使用附加函数 selectDepartment
将值传递给可观察对象,而应直接将可观察对象绑定(bind)到选择框的 value 属性:
<select data-bind="options:departments, value:selectedDepartment, ...
(记住导出 selectedDepartment
可观察对象)
value 属性不仅用于将当前值从 View 传递到 View 模型,反之亦然:设置选定的选项。因此,绑定(bind)到仅提供“写入”功能的函数是不够的。
如果您需要对所选部门的变化使用react,您可以订阅 observable(官方文档中有解释)。
关于javascript - KnockoutJS - 将值加载到下拉列表。所选值始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26570138/