Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS visible not working for me

Tags:

knockout.js

Below is some table code. I don't want the row to show if the Id of the data item is 0. I tried writing it like this:

data-bind="visible: $data.Id > 0"

But that's not working. Nor did putting the 0 in quotes. I also tried:

data-bind="visible: $index > 0"

But that makes all rows go away! I'm sure this is a simple syntax issue, but I'm not seeing it...

    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>URL</th>
                <th>Disabled</th>
                <th>Parent</th>
                <th></th>
            </tr>
        </thead>
        <tbody data-bind="foreach: menuItemModels">

            <tr  data-bind="visible: $data.Id > 0">

                <td>
                    <input type="text" class="input-block-level" data-bind="value: $data.Name" /></td>
                <td>
                    <input type="text" class="input-block-level" data-bind="value: $data.Url" /></td>
                <td style="text-align: center;">
                    <input type="checkbox" data-bind="value: $data.Disabled" /></td>
                <td>                      
                    <select data-bind="options: $root.menuItemModels, optionsValue: 'Id', optionsText: 'Name', value: ParentId"></select>
                </td>
                <td>
                    <button class="btn btn-primary" type="submit"data-bind="click: $root.update">Update</button>
                    <button class="btn btn-primary" type="submit" data-bind="click: $root.remove">Delete</button>
                </td>
            </tr>
        </tbody>
    </table>
like image 821
Todd Davis Avatar asked Jan 15 '23 05:01

Todd Davis


1 Answers

When you access an observable's value in an expression, then you need to call it as a function.

If Id is observable, then you need to call it like $data.Id() > 0.

The visible binding does work off of whether the value is truthy/falsy though, so you really can just reduce it to visible: Id. When you pass a simple observable to a binding (not in an expression), then Knockout unwraps it (calls it as a function) for you.

$index is also an observable, so it would be the same idea like: visible: $index

like image 86
RP Niemeyer Avatar answered Jan 22 '23 10:01

RP Niemeyer