The following KnockoutJS foreach in select:
<select "foreach: ControllersAndActions">
<optgroup data-bind="attr: {label: $data.ControllerName}, foreach: Actions">
<option data-bind="text: $data"></option>
</optgroup>
</select>
renders the options tree styled the following way:
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<optgroup>
<optgroup label="NFC NORTH">
<option>Chicago Bears</option>
</optgroup>
I need to do just that, except to also insert an initial empty option before the groups start, like this:
<option value=""></option>
<optgroup label="NFC EAST">
<option>Dallas Cowboys</option>
<optgroup>
How can I inject a singe item that is not “re-rendered” each time a foreach loop iterates?
Don’t put the
foreachbinding on theselectelement instead of add the “foreach one level deeper” (e.g with using the containerless control flow syntax) and manually add the empty element:You can see it in action in this JSFiddle.