Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
Jamie Hutber Avatar asked Feb 18 '26 08:02

Jamie Hutber


1 Answers

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.

like image 173
nemesv Avatar answered Feb 19 '26 21:02

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!