2017-05-31 205 views
0

我有2個選擇菜單。一個選擇一個,另一個選擇多個選項。KnockoutJS - 選擇菜單多個選項

當第一個被選中時,它應該自動選擇第二個菜單中的相關選項。

因此,舉例來說,如果「ManualItems」時,它應該然後標記「分析師」和「主管」作爲第二選擇菜單中選擇。

這兩個菜單都沒有成功綁定,所以我不知道我錯過了什麼。

<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()); 

JSFiddle

回答

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); 
}); 

Updated Fiddle