剔除JS选项数据绑定多个值

时间:2018-08-27 00:07:30

标签: knockout.js

我想在data-tokens属性中添加多个值:

<option data-bind="text: customer_display_name, value: customer_id, attr: {'data-tokens': customer_first_name, customer_last_name}"></option>

不幸的是,这无法正常工作,只有数据令牌“ customer_first_name”有效,而“ customer_last_name”无效。 如何添加多个值?

编辑: 我也想在选项绑定中做同样的事情:

<select class="form-control selectpicker" data-live-search="true"
    data-bind="options: $parent.customers, optionsText: 'customer_display_name', optionsValue: 'customer_id', value: customer_id,
    event: {change: $parent.changeWorkCustomer}, attr: {'data-tokens': [$parent.customer_first_name, $parent.customer_last_name]}, css: { customer_fav: $parent.fav > 0 }">

它不能像这样工作。谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您还可以通过将它们包装在数组中,然后通过调用它们的值来unwrap来做到这一点:

data-bind="attr: {'data-tokens': [attr1(), attr2()]}

ko将弄清楚需要做什么并输出多个值:

function MyViewModel() {
  this.attr1 = ko.observable('test1')
  this.attr2 = ko.observable('test2')
}
ko.applyBindings(new MyViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="attr: {'data-tokens': [attr1(), attr2()]}">Testing!</div>
<input type="text" data-bind="value: [attr1(), attr2()]" />

如果您在inspect element上进行Testing!,则会看到结果是:

data-tokens="test1,test2"

答案 1 :(得分:0)

您是说要两个变量的值都用逗号隔开?

尝试一下:

attr: {'data-tokens': (customer_first_name + ', ' + customer_last_name)}