首页 > 解决方案 > 带有打字稿和敲除(foreach)的选择框模型

问题描述

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

我遵循了这种方式: 带有打字稿和淘汰赛的选择框模型

我的典型打字稿:

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>

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

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

提前感谢您的任何帮助<3

标签: typescriptknockout.js

解决方案


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

顺便说一句,你的choicesobservable 应该是一个 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>


推荐阅读