Add extra attribute to option through Knockout

2019-07-25 17:30发布

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>

标签: knockout.js
1条回答
我命由我不由天
2楼-- · 2019-07-25 18:17

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.

查看更多
登录 后发表回答