knockout "if binding" not working
Asked Answered
I

2

9

When debugging with Chrome, I can see CoverPrices has 9 elements. The foreach loop actually works well and the table looks correct with the first span being bound to Item1 correctly.

However, the if binding does not work and both images are displayed. Yet, all the elements in Item2 have the true value, so only the first image should show up.

<!-- ko foreach: CoverPrices -->
    <tr>
        <td>
            <span data-bind="text: Item1"></span>
        </td>
        <!-- ko foreach: Item2 -->
        <td>
            <img src="~/Images/yes.png" alt="oui" data-bind="if: $data" /> 
            <img src="~/Images/no.png" alt="non" data-bind="ifnot: $data" /> 
        </td>
        <!-- /ko -->
    </tr>
    <!-- /ko -->

Is there something wrong with my binding ?

Incorporating answered 13/3, 2013 at 10:32 Comment(1)
Can you post how is your Item2 collection look like?Kora
B
31

The if-binding does not affect the whole element, but its content. And because an img element does not have content, the binding does not matter.

This will work, with span as container elements:

<span data-bind="if: $data"><img src="~/Images/yes.png" alt="oui" /></span>
<span data-bind="ifnot: $data"><img src="~/Images/no.png" alt="non" /></span>

There is also a container-less syntax, if you don't want the additional elements:

<!-- ko if: $data -->
    <img src="~/Images/yes.png" alt="oui" />
<!-- /ko -->
<!-- ko ifnot: $data -->
    <img src="~/Images/no.png" alt="non" />
<!-- /ko -->
Bookcraft answered 13/3, 2013 at 10:39 Comment(5)
Or use the visible binding instead?Dickens
@PaulManzotti valid point, in this code there is no reason to use "if" because there are no other bindings involved.Bookcraft
@fab thanks for the explanation, that makes sense. I ended up using visible binding as it seems more appropriate in this case indeedIncorporating
Nice, this one had me scratching my head for a few minutes.Henke
Not the element but its content... 2 hours of my life I'll never get back!Luettaluevano
L
0

Image is not binding to DOM, but the image is loading. You can check in Network traffic. It should not load when if bind is used

Lor answered 9/2, 2016 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.