KnockoutOut JS - why are these values not binding

2019-09-04 11:15发布

问题:

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:

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>

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.

回答1:

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>