我有一个多选组件,我用“选项”绑定(bind)绑定(bind)了它,“选项”会根据我在另一个多选组件中选择的值进行刷新。 下面是第一个多选组件
<select data-bind="multiple: true, required: true, options:repositoriesForSelect, value: selectedRepository"></select>
根据这个组件中选择的值,正在刷新第二个组件的选项
<select data-bind=" multiple: true,required: true,options: branchesForSelect,value: selectedBranch"></select>
使用计算变量刷新第二个选项:
branchesForSelect = ko.computed(function(){
//selectedRepository is an observable array here
//some logic
});
效果很好,但除上述之外,我想根据在同一组件中选择的值刷新“branchesForSelect”。意思是,如果“branchesForSelect”包含值“A”、“B”、“C”,那么在选择“A”时,我想刷新“branchesForSelect”以在选项列表中仅显示“C”。
有人可以指导我吗?如果问题不清楚,请在评论中告诉我。
谢谢
最佳答案
通过计算第二个选项列表,您走在了正确的轨道上。这是您仍然需要做的:在计算的内部,使用 selectedRepository
的值来返回链接到选择的选项数组。通过使用此值,knockout 将确保在第一个选择的 value
变量发生更改后,重新评估第二个选项列表。
在评论中澄清问题后:
从用户体验的 Angular 来看(如果您问我),在用户输入后更改选择本身的值是一个坏主意,但肯定可以做到。下面的代码将向您展示如何操作。当多选的第一个选项处于事件状态时,其他选项将被隐藏。
这是一个例子:
var repositoryBranches = {
a: ["All", 1, 2, 3, 4, 5, 6],
b: ["All", 0, 7, 8],
c: ["All", 9, 10]
};
var VM = function() {
var self = this;
this.repositoryKeys = ["a", "b", "c"];
this.selectedRepository = ko.observable("a");
this.selectedBranches = ko.observableArray([]);
this.branchesForSelectedRepository = ko.computed(function() {
var allBranchesForRepo = repositoryBranches[self.selectedRepository()];
// We're making an exception if the first one is selected:
// don't show any other options if the selected one is the first one
if (self.selectedBranches()[0] === allBranchesForRepo[0]) {
return ["All"];
}
return allBranchesForRepo;
});
// Clear selection when changing repository
this.selectedRepository.subscribe(function clearSelection() {
self.selectedBranches([]);
});
};
ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options:repositoryKeys, value: selectedRepository"> </select>
<select multiple="true" data-bind="options:branchesForSelectedRepository, selectedOptions: selectedBranches"></select>
( fiddle )
如果您需要帮助找到一种将“分支”链接到“存储库”的好方法,请告诉我。理想情况下,“存储库”有自己的模型,其中包含一系列“分支”。然后您就可以定义您的计算数组,例如 return self.firstSelection().branches;
关于javascript - 如何刷新 ko 多选组件中的 'options' 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36589445/