如何使用Knockout.js在OptionText中显示多文本 [英] How to show multilpe text in OptionText with Knockout.js

查看:47
本文介绍了如何使用Knockout.js在OptionText中显示多文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

<select name="test" id="test" class="" 
    data-bind="
    options: myArray, 
    value: idSelected,
    optionsText: 'name',
    optionsValue: 'id',
    optionsCaption: 'All'>
</select>

结果:

text 1
text 2
text 3
...

我想要concat ID并用'-'命名.我想要这个:

I want concat Id and name with '-' . I want this:

1 - Text 1
2 - text 2
3 - text 3
...  

推荐答案

您可以创建 computed 属性并将其绑定到options.

这是一个有效的代码段:

Here's a working snippet:

var viewModel = function() {
  var self = this;
  self.idSelected = ko.observable();
  self.myArray = ko.observableArray([{
    name: "Text 1",
    id: 1
  }, {
    name: "Text 2",
    id: 2
  }]);
  
  // bind this to the options
  self.computedArray = ko.computed(() => {
    return self.myArray().map(function(item) {
      return {
        name: item.id + ' - ' + item.name,
        id: item.id
      }
    });
  })
}

ko.applyBindings(new viewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select name="test" id="test" class="" data-bind="
                   options: computedArray, 
                   value: idSelected,
                   optionsText: 'name',
                   optionsValue: 'id',
                   optionsCaption: 'All'">
</select>

(如果您使用的是剔除工具3.2,也可以使用 pureComputed +)

(You can also use pureComputed if you're using knockout 3.2+)

这篇关于如何使用Knockout.js在OptionText中显示多文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆