Knockout选择列表 - 指定默认值

时间:2018-05-11 18:57:05

标签: knockout.js knockout-3.0

将数据绑定到带有对象的选择列表时,如何指定默认值?

我正在尝试以下方式:

var Country = function(name, population) {
  this.countryName = name;
  this.countryPopulation = population;
};

var viewModel = {
  availableCountries: ko.observableArray([
    new Country("UK", 65000000),
    new Country("USA", 320000000),
    new Country("Sweden", 29000000)
  ]),
  selectedCountry: ko.observable(new Country("USA", 320000000))
};

<select data-bind="options: availableCountries,
                   optionsText: 'countryName',
                   value: selectedCountry,
                   optionsCaption: 'Choose...'"></select>

我的想法是availableCountries将包含一个Country个对象数组,所选对象将保存在selectedCountry可观察对象中。

除了预先选择列表中的值之外,一切都按预期工作。

我希望它不起作用,因为它们实际上是不同的对象引用。什么是最简洁,最简单的方法?我希望默认选择美国国家。

这是一个解释问题的小提琴: https://jsfiddle.net/85crLcy2/

1 个答案:

答案 0 :(得分:2)

您可以拆分选择数组,然后将selectedCountry设置为USA选项:

var choices = [
    new Country("UK", 65000000),
    new Country("USA", 320000000),
    new Country("Sweden", 29000000)
  ];
var viewModel = {
  availableCountries: ko.observableArray(choices),
  selectedCountry: ko.observable(choices[1])
};