KnockoutJs:根据下拉选择创建复选框列表

时间:2014-03-21 13:52:03

标签: javascript knockout.js

我有一个GeneNames列表,将用于select控件的数据绑定选项

(GeneDropdownOptions:)
["CYP2D6","CYP2C19","CYP3A4","COMT","CACNA1C","MTHFR","ANK3","5HT2C","DRD2","SLC6A4"]

<!-- ko foreach: $root.AssaySelectedGenes -->
    <div class="form-group">
        <label data-bind='uniqueFor: true'>Gene:</label>
        <select class="form-control" data-bind='uniqueName: true, options: $root.GeneDropdownOptions, value: $data, optionsCaption: "Select Gene"'></select>                       
    </div>
<!-- /ko -->

根据从下拉列表中选择的GeneName值,我需要能够从此键值对数据集合中生成Snips的复选框列表

(SnipCheckboxOptions:)
[{"GeneName":"CYP2D6","Snips":["CYP2D6*2","CYP2D6*3","CYP2D6*4","CYP2D6*5","CYP2D6*6","CYP2D6*9","CYP2D6*10","CYP2D6*17","CYP2D6*41"]},{"GeneName":"CYP2C19","Snips":["CYP2C19*2","CYP2C19*3","CYP2C19*17"]},{"GeneName":"CYP3A4","Snips":["CYP3A4*3","CYP3A4*6","CYP3A4*7"]},{"GeneName":"COMT","Snips":["COMT"]},{"GeneName":"CACNA1C","Snips":["CACNA1C"]},{"GeneName":"MTHFR","Snips":["MTHFR"]},{"GeneName":"ANK3","Snips":["ANK3"]},{"GeneName":"5HT2C","Snips":["5HT2C"]},{"GeneName":"DRD2","Snips":["DRD2"]},{"GeneName":"SLC6A4","Snips":["SLC6A4*1","SLC6A4*2"]}]

有人可以通过指向类似示例或投掷jsfiddle演示来协助此功能。感谢

1 个答案:

答案 0 :(得分:1)

查看: -

<div class="form-group">
   <label data-bind='uniqueFor: true'>Gene:</label>
   <select class="form-control" data-bind='uniqueName: true, options: $root.GeneDropdownOptions, value: selectedGene, optionsCaption: "Select Gene"'></select>
</div>
<!-- ko foreach: snipData().Snips -->
   <input type="checkbox" data-bind="value: $data,checked:$parent.checkedSnips" />
   <span  data-bind="text:$data"></span>
   <br/>
<!-- /ko -->
<pre data-bind="text: ko.toJSON(checkedSnips)"></pre>

视图模型: -

var Vm = function () {
  var self = this;
  self.GeneDropdownOptions = ko.observableArray(genes);
  self.selectedGene = ko.observable();
  self.SnipCheckboxOptions = ko.observableArray(snipData);
  self.checkedSnips = ko.observableArray([]);
  self.snipData = ko.dependentObservable(function () {
    var gene = self.selectedGene(),
        arr = [];
    self.checkedSnips.removeAll();
    if (gene && gene !== "") {
        arr = ko.utils.arrayFirst(self.SnipCheckboxOptions(), function (i) {
            return i.GeneName === gene;
        });
    }
    return arr || [];
  });

}
 ko.applyBindings(new Vm());

Fiddle Demo