如何使用敲除将所选选项传递给可观察数组

How to pass selected option using knockout to an observable array

我正在尝试使用 knockout js 将下拉列表的 selected 值传递到我的视图模型。

<select class="form-control" style="width:auto" data-bind="options: clients, optionsCaption: 'Choose...', optionsText: 'name', optionsValue: 'value', value: 'selectedCustomer'"></select>

在我的视图模型中,我声明了一个 ko observable 来存储 selected 值:

self.selectedCustomer = ko.observableArray([]);

当我 select 一个值时,变量没有被填充。有小费吗?谢谢!

我发现代码有两个问题:

您将值绑定到 observableArray,但所选选项将是单个客户,因此应改用 observable

值 (value: 'selectedCustomer') 也不应该用单引号引起来,因为这样您实际上是在尝试绑定到字符串而不是可观察对象。

试试下面的方法:

<select class="form-control" style="width:auto" data-bind="options: clients, optionsCaption: 'Choose...', optionsText: 'name', optionsValue: 'value', value: selectedCustomer"></select>

然后在视图模型中:

self.selectedCustomer = ko.observable();