typescript - 带有打字稿和敲除(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
解决方案
我认为您正在寻找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>
推荐阅读
- node.js - 在由节点渲染的元素上添加事件监听器
- javascript - 如何在手机 P5 中使用 mousePressedOver?
- javascript - 通过 URL 传递访问变量以更新 Grafana 的数据源 URL
- r - Is there no way to import highcharts objects in highcharter?
- ios - 当前子视图控制器
- reactjs - Typescript i18next 不满足约束 'string | TemplateStringsArray NextJS
- flutter - 根据列表视图构建器中另一个单击的反应按钮的值更改反应按钮中的表情符号
- sql-server - 最终用户启动 SQL 命令以从 SQL 表创建文件?
- javascript - on(click) 事件委托 .forEach Array.from 只显示被点击的元素
- dart - 如何在以下代码中修复此错误?