Knockout Components选择选项

时间:2014-12-17 23:09:53

标签: javascript knockout.js knockout-components

我一直在撕开我的头发,有人可以救我......

我想创建一个简单的挖空组件,它根据JSON对象呈现一个选择列表。 这在我使用简单的字符串数组时有效,但是当我使用JSON对象时,使用optionsText和optionsValue绑定了id和name属性,我得到了一个带有[object object]的下拉列表。

非常感谢任何帮助。

        ko.components.register("organization-select", {
            viewModel: function (params) {
                var self = this;
                self.organizationList = ko.observableArray([]);
                self.organizationList(["foo", "bar"]); //this works

                //this doesn't work Result => [Object Object],[Object Object]
                self.organizationList([{ "id": 1, "name": "foo" }, { "id": 2, "name": "bar" }]); 
            },

            template: 'Organizations: <select data-bind="options: organizationList, optionsText: "name", optionsValue: "id""></options>'
            //this works with simple array of strings
            //template: 'Organizations: <select data-bind="options: organizationList"></options>'
        });
        ko.applyBindings();
    });

1 个答案:

答案 0 :(得分:2)

行情看起来搞砸了:

template: 'Organizations: <select data-bind="options: organizationList, optionsText: "name", optionsValue: "id""></options>'
// Here ------------------------------------^ but then ------------------------------^

...所以data-bind选项实际上只包含

data-bind="options: organizationList, optionsText: "

您需要转义那些嵌入式引号。可能最简单的方法是使用转义单曲:

template: 'Organizations: <select data-bind="options: organizationList, optionsText: \'name\', optionsValue: \'id\'"></options>'