Ho trovato un esempio here per creare un elenco di selezione con optgroups utilizzando KnockoutJS. Questo funziona bene, ma voglio associare il valore della discesa per il mio proprio oggetto JavaScript, quindi accedere a una particolare proprietà di tale oggetto:KnockoutJS - Valore di binding della selezione con oggetti optgroup e javascript
<select data-bind="foreach: groups, value:selectedOption">
<optgroup data-bind="attr: {label: label}, foreach: children">
<option data-bind="text: label"></option>
</optgroup>
</select>
function Group(label, children) {
this.label = ko.observable(label);
this.children = ko.observableArray(children);
}
function Option(label, property) {
this.label = ko.observable(label);
this.someOtherProperty = ko.observable(property);
}
var viewModel = {
groups: ko.observableArray([
new Group("Group 1", [
new Option("Option 1", "A"),
new Option("Option 2", "B"),
new Option("Option 3", "C")
]),
new Group("Group 2", [
new Option("Option 4", "D"),
new Option("Option 5", "E"),
new Option("Option 6", "F")
])
]),
selectedOption: ko.observable(),
specialProperty: ko.computed(function(){
this.selectedOption().someOtherProperty();
})
};
ko.applyBindings(viewModel);
Grazie mille! – user888734
Grazie per il tuo aiuto! Semplice ed efficiente. – Mounir
Come aggiungerebbe "optionsCaption" a questa soluzione? @RP Niemeyer –