Showing a concatenated string from multiple values

2019-07-07 17:20发布

I have an observable array as follows..

var myObservableArray = ko.observableArray([
    { name: "Bungle", type: "Unknown" },
    { name: "George", type: "Unknown" },
    { name: "Zippy", type: "Unknown" }
]); 

I wish to fill a select listbox from elements in the observable array such that the option names are concatenated string of 'name' and 'type' like "Bungle-Unknown","George-Unknown",.etc The optionvalues are just 'name'.

Any help is sincerely appreciated.

Thanks

1条回答
Root(大扎)
2楼-- · 2019-07-07 17:53

In your binding on the select control, you can use the optionsText binding to build up the caption for your options (see http://knockoutjs.com/documentation/options-binding.html, example 4). You could basically do this (assuming you have another observable called selected to hold the selected option from your dropdown):

<select data-bind="options: myObservableArray,
                   optionsText: function(item) {
                       return item.name + '-' + item.type;
                   },
                   value: selected"></select>
查看更多
登录 后发表回答