我有2个选择菜单。一个选择单选,另一个选择选择。
当选择第一个时,它应该在第二个菜单中自动选择那些相关选项。
例如,如果" ManualItems "如果选中,则应标记" Analyst "和" 主管"在第二个选择菜单中选择。
这两个菜单都没有成功绑定,所以我不确定我错过了什么。
<div class="form-group">
<label for="taskName">Edit Existing Task</label>
<select class="form-control" id="taskNameSelect"
data-bind="options: tasks,
optionsText: 'TaskName',
value: currentTask,
optionsCaption: 'Select Task...'"></select>
</div>
<div class="form-group">
<label for="editApprovalLevelList">Select Approval Levels</label>
<select multiple="multiple" class="form-control" id="editApprovalLevelList"
data-bind="options: availableApprovalLevels,
selectedOptions: userSelectedApprovalLevels,
optionsText: 'ApprovalLevelName',
optionsvalue: 'ApprovalLevelName'"></select>
</div>
var viewModel = function(data) {
var self = this;
// variables
self.currentTask = ko.observable();
self.userSelectedApprovalLevels = ko.observable[];
self.tasks = ko.observableArray([
{TaskID: 1, TaskName: "ManualItems", ApprovalLevels:[{"ApprovalID": 1},{"ApprovalID": 2}]},
{TaskID: 1, TaskName: "Trades", ApprovalLevels:[{"ApprovalID": 2}]},
{TaskID: 1, TaskName: "Positions", ApprovalLevels:[{"ApprovalID": 1},{"ApprovalID": 3}]},
]);
self.availableApprovalLevels = ko.observableArray([
{ApprovalID: 1, ApprovalLevelName: "Analyst"},
{ApprovalID: 2, ApprovalLevelName: "Supervisor"},
{ApprovalID: 3, ApprovalLevelName: "Manager"}
]);
self.currentTask.subscribe(function (task) {
var matchingApprovalLevel = ko.utils.arrayFirst(self.availableApprovalLevels(), function (approvalLevel) {
return approvalLevel.ApprovalID === task.ApprovalID;
});
self.userSelectedApprovalLevels(matchingApprovalLevel);
});
};
ko.applyBindings(new viewModel());
答案 0 :(得分:0)
您的示例中还有许多其他问题,但忽略这些问题,如果您希望多项选择有效,则应生成所选值的数组。您最初是根据任务的ApprovalID
选择批准级别。但是任务没有批准ID,它有一系列批准级别。
self.currentTask.subscribe(function (task) {
var selected = ko.utils.arrayMap(task.ApprovalLevels, function(a) {
return ko.utils.arrayFirst(self.availableApprovalLevels(), function (ta) {
return a.ApprovalID === ta.ApprovalID;
});
});
self.userSelectedApprovalLevels(selected);
});