我的头发都快掉光了,谁能救救我吗?
我想创建一个简单的 knockout 组件,它呈现基于 JSON 对象的选择列表。 当我使用简单的字符串数组时,这是有效的,但是当我使用 JSON 对象,并且使用 optionsText 和 optionsValue 绑定(bind) 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();
});
最佳答案
引用看起来很困惑:
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>'
关于javascript - knockout 组件选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27536537/