Jamie Hutber
Jamie Hutber

Reputation: 28076

Knockout.js - How bind a data-var in a foreach

I would like to bind data-id to my looped items in knockout

    <ul data-bind="foreach: items">
        <li data-bind="attr: {data-id: $data.id}">
            <p data-bind="text: title"></p>
            <img alt="" data-bind="attr: {src: $data.img}">
            <h4>Volkswagen.co.uk</h4>
        </li>
    </ul>

<li data-bind="attr: {data-id: $data.id}"> So specifically this line of code is what I would like to get working.

Upvotes: 3

Views: 1181

Answers (1)

nemesv
nemesv

Reputation: 139758

Because data-id is not a legal identifier name in JavaScript you need to write:

<li data-bind="attr: { 'data-id' : $data.id}">

See attr binding documentation Applying attributes whose names aren’t legal JavaScript variable names section.

Upvotes: 3

Related Questions