我已在我的主视图模型中将我的视图模型建模为POJO和页面范围的函数。我想显示所选的部门名称。
我的选择绑定到根视图模型上的类型列表。所选项目绑定到部门的可观察属性。
如何从根视图模型的数组中检索名称并显示它?
<div data-bind="with: department">
Department Type
<select data-bind="options: $root.departmentTypes, optionsText: 'name', optionsValue: 'id', value: departmentTypeId, optionsCaption: 'Select....' "></select>
<!--I want to display the name that was selected here-->
<span data-bind="departmentName"></span>
</div>
var Department = function() {
var self = this;
self.name = ko.observable();
self.departmentTypeId = ko.observable();
self.departmentName = ko.computed(/* using the departmentTypeId search the list of departments on the view model and display the name that was selected*/ );
};
var VieWModel = function () {
var self = this;
self.saveDepartment = function(){ /* save self.department to the server using ajax */ };
self.departmentTypes = [
{ id: 1, name: 'core' },
{ id: 2, name: 'support' },
{ id: 3, name: 'income' },
];
self.department = new Department();
};
$(function() {
ko.applyBindings(new ViewModel());
});
答案 0 :(得分:0)
你必须使用observableArray。无需使用&#34;使用&#34;关键字。
var DepartmentType = function (id, name) {
var self = this;
self.name = name;
self.departmentId = id;
}
var Department = function() {
var self = this;
self.name = ko.observable();
self.department = ko.observable();
self.departmentName = ko.computed(function() {
return self.department().name;
}, this);
self.departmentId = ko.computed(function () {
return self.department().id;
}, this);
};
var VieWModel = function () {
var self = this;
self.departmentTypes = ko.observableArray([
{ id: 1, name: 'core' },
{ id: 2, name: 'support' },
{ id: 3, name: 'income' },
]);
self.selectedDepartmentType = ko.observable();
self.saveDepartment = function () {
//check if self.selectedDepartmentType() is not null
//call your server sending self.selectedDepartmentType().id
}
};
HTML
<select data-bind="options: departmentTypes, optionsText: 'name', optionsValue: 'id', value: selectedDepartmentType, optionsCaption: 'Select....' "></select>
<!-- check if selectedDepartment is not null, then show its name -->
<span data-bind="text: selectedDepartmentType() ? selectedDepartmentType().name: 'unknown'"></span>