nick gowdy
nick gowdy

Reputation: 6531

KnockoutOut JS - why are these values not binding correctly?

I have this knockout observable array and I am trying to bind some of its values to my view. Where I am having difficulties is because its nested. I am not sure what the correct data-bind syntax is.

This is my observable array data:

data

I want to bind advertiserName within advertiser.

This is my HTML

<table id="tblBrand">
        <thead>
            <tr>
                <th>Brand Name</th>
                <th>
                    <button data-bind='click: $root.addBrand'>Add Brand</button></th>
            </tr>

        </thead>
        <tbody data-bind="foreach: brands">
            <tr>
                <td>
                    <input data-bind="value: brandName" readonly="true" />
                </td>
            </tr>
            <tr>
                <td>
                    <table>
                        <tr>
                            <td>
                                <input data-bind="value: advertiser.advertiserName" />
                            </td>

                            <td>
                                <input data-bind="value: advertiser.advertiserRank" />
                            </td>
                        </tr>
                    </table>
                    <td>
                        <a href='#' data-bind='click: $root.removeBrand' style="color: blue">Remove</a>
                    </td>
            </tr>
        </tbody>
    </table>

Page and HTML

The way my binding works is I am looking within each brand. Each brand has an advertiser object and I want to drill into that. The second screenshot shows my syntax and what the page renders.

Upvotes: 0

Views: 62

Answers (1)

nemesv
nemesv

Reputation: 139798

Because your advertiser is ko.observable you need to get its value with advertiser() if you are using it inside an expression:

<table>
   <tr>
       <td>
           <input data-bind="value: advertiser().advertiserName" />
       </td>
       <td>
           <input data-bind="value: advertiser().advertiserRank" />
       </td>
   </tr>
</table>

Or you can use the with binding:

<table data-bind="with: advertiser">
   <tr>
       <td>
           <input data-bind="value: advertiserName" />
       </td>
       <td>
           <input data-bind="value: advertiserRank" />
       </td>
   </tr>
</table>

Upvotes: 1

Related Questions