KnockoutJS Foreach包含不更新ViewModel的Options绑定



我正在尝试在KO中的foreach绑定中使用嵌套的options、(optionsTextoptionsValue)和value绑定。

我希望下面的代码将选择框绑定到ViewModel的相关Item,但它似乎没有更新视图模型中的值-它们总是保持我用"n/a"初始化的值-我该怎么做?

我已经设置了一个html页面如下:

<table>
    <tbody data-bind="foreach: Items">
        <tr>
            <td>
                <select data-bind="options: $parent.Countries, optionsText: 'Name', optionsValue: 'Code', value: 'Country'"></select>
            </td>
            <td>
                <span data-bind="text: Country"></span>                    
            </td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="2">
                <a href="#" data-bind="click: AddItem">Add item</a>
            </td>
        </tr>
    </tfoot>
</table>

使用以下JavaScript:

var countries = ko.observableArray([
    { Name : "United Kingdom", Code : "UK", Population : "1 Monarch" },
    { Name : "Australia", Code : "AU", Population : "22 million kangaroos" },
    { Name : "Antarctica", Code : "AQ", Population : "100,000 penguins (0 polar bears)" }
]);
var item = { Country : "n/a" };
var ViewModel = function() {
    this.Countries = countries;
    this.Items = ko.observableArray();
    this.AddItem = function() {
        this.Items.push(ko.mapping.fromJS(item));
    };
};
var vm = new ViewModel();
ko.applyBindings(vm);

小提琴在这里

value绑定中删除引号:

<select data-bind="options: $parent.Countries, 
                   optionsText: 'Name', 
                   optionsValue: 'Code', 
                   value: Country"></select>

这是工作小提琴:链接

最新更新