带有打字稿和剔除(foreach)的选择框模型

时间:2018-11-05 16:05:35

标签: typescript knockout.js

我正在使用Knockout和Typescript。我有一个具有多个输入和一个选择标记的表单。对于输入数据,仅通过名称绑定数据就很容易。但是对于选择标签(下拉列表),它并不是那么明显。 我尝试为foreach中的多个对象的下拉列表设置默认选项。

我按照这种方式:Selection box model with typescript and knockout

我的示范打字稿:

export class ViewModel {
choices = ko.observable([
    { id: 1, hour: "01:00", choice: false },
    { id: 2, hour: "02:00", choice: false },
    { id: 3, hour: "03:00", choice: false },
    { id: 4, hour: "04:00", choice: false },
    { id: 5, hour: "05:00", choice: false },
    { id: 6, hour: "06:00", choice: false },
    { id: 7, hour: "07:00", choice: false },
    { id: 8, hour: "08:00", choice: false },
    { id: 9, hour: "09:00", choice: false },
    { id: 10, hour: "10:00", choice: false },
]);
selectedChoice = ko.observable(10);
selectedHours = ko.observable([1, 5, 7]);

constructor() {
    this.config = new ServiceConfigurationModel();
    this.getConfiguration();
    this.selectedChoice.subscribe(function (newValue) {
        alert("the new value is " + newValue);
    });
}
}

当我在HTML中有此行时:

<select data-bind="options: choices, optionsText: 'hour', optionsValue: 'id',  value: selectedChoice"></select>

但是,当我想使用<!-- ko foreach: selectedHours() -->对每个selectedHours数组重复一次时,它不起作用

您是否有提示如何在不重复整个代码的情况下为多个下拉列表设置此选项?

在此先感谢您的帮助<3

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找selectedOptions绑定吗?

顺便说一句,您的choices的observable应该是一个observableArray。还有selectedHours

function viewmodel(){
  this.choices = ko.observableArray([
    { id: 1, hour: "01:00", choice: false },
    { id: 2, hour: "02:00", choice: false },
    { id: 3, hour: "03:00", choice: false },
    { id: 4, hour: "04:00", choice: false },
    { id: 5, hour: "05:00", choice: false },
    { id: 6, hour: "06:00", choice: false },
    { id: 7, hour: "07:00", choice: false },
    { id: 8, hour: "08:00", choice: false },
    { id: 9, hour: "09:00", choice: false },
    { id: 10, hour: "10:00", choice: false },
  ]);
  //selectedChoice = ko.observable(10);
  this.selectedHours = ko.observableArray([1, 5, 7]);
  this.selectedHours.subscribe(function (newValue) {
        //alert("the new value is " + newValue);
        console.log("the new value is " + newValue);
  });
  this.clear = function(){
      console.clear();
  };
};

ko.applyBindings(viewmodel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: choices, 
                   optionsText: 'hour', 
                   optionsValue: 'id',  
                   selectedOptions: selectedHours" 
        multiple="true" 
        style="height: 150px"></select>
 <button data-bind="click: clear" style="float: right">Clear</button>