Add extra attribute to option through Knockout

2019-07-25 18:28发布

问题:

I have the Need for an extra value of an Option. the following select is being populated through the options: groupItems, which contains an 'id', a 'description' and a 'period'.

    <select name="cb_group_1130" id="cb_group_1130" data-bind="options: groupItems(1130), optionsText : 'description',  optionsValue : 'id', optionsPeriod : 'period', value : selectedItem(1130)">
    <option value="0">First</option>
    <option value="1637">second</option>
    <option value="1638">third</option
</select>

in the above case the optionsPeriod: 'period' doesnt work...

I want to accomplish that the Knockout generated Option displays this:

<option value="0" period="2" >First</option>

回答1:

You need to use the optionsAfterRender option to post process the rendered option elements:

And in your view model:

this.setPeriod = function (option, item) {
        ko.applyBindingsToNode(option, {
            attr: {
                period: item.period
            }
        }, item);
    }

Demo JSFiddle.



标签: knockout.js