如何在knockoutjs中使用object设置选项值

时间:2017-12-07 03:24:02

标签: knockout.js

我有:

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

我不想只有id,我想在列表中选择一个项目时在对象中设置我的数组的id和名称。样品:

我想要这个结果:

  idSelected = {id:1, name:'Test'};

1 个答案:

答案 0 :(得分:3)

只需从绑定中删除optionsValue即可。这会将idSelected设置为observableArray的对象而不是字符串(documentation

这是一个工作片段:

&#13;
&#13;
var viewModel = function() {
  var self = this;

  self.myArray = ko.observableArray([{
    id: 1,
    name: 'Test 1'
  }, {
    id: 2,
    name: 'Test 2'
  }]);

  self.idSelected = ko.observable();

  self.idSelected.subscribe((selected) => {
    console.log(self.idSelected());
  });
}

ko.applyBindings(new viewModel());
&#13;
<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: myArray, 
  value: idSelected,
  optionsText: 'name',
 optionsCaption: 'All'">
&#13;
&#13;
&#13;