How to show multilpe text in OptionText with Knock

2019-07-29 04:36发布

问题:

I have this code:

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

Result:

text 1
text 2
text 3
...

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

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

回答1:

You can create a computed property and bind that to 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>

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



标签: knockout.js