Alvaro
Alvaro

Reputation: 41595

If statement in knockout.js not working as expected

I'm trying to display the string "No data was found." inside a table row whenever the data array is empty, but it seems the message get always printed no matter what.

Reproduction online (ignoring the condition orders.length ==0)

What am I doing wrong?

<table>
    <thead>
        <tr>
            <th>Truck</th>
            <th>Pickup</th>
        </tr>
    </thead>
    <!-- ko if: orders.length==2 -->
    <tbody>
        <tr colspan="2">No data was found.</tr>
    </tbody>
    <!-- /ko -->
    <tbody data-bind="foreach: orders">
        <tr>
            <td data-bind="text: truck"></td>
            <td></td>
        </tr>
    </tbody>
</table>

Upvotes: 0

Views: 86

Answers (1)

nemesv
nemesv

Reputation: 139748

If your orders is an ko.observableArray you need to write orders() to get the underlying array and get the length from there:

<!-- ko if: orders().length== 0 -->

Your HTML also invalid, the td elements are missing from:

<!-- ko if: orders().length==0 -->
    <tbody data-bind="if: orders().length==0">
        <tr colspan="2"><td>No data was found.</td></tr>
    </tbody>
<!-- /ko -->

Demo JSFiddle.

Upvotes: 2

Related Questions