KnockoutOut JS - why are these values not binding correctly?

别说谁变了你拦得住时间么 提交于 2019-12-14 04:26:07

问题


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>


来源:https://stackoverflow.com/questions/18762396/knockoutout-js-why-are-these-values-not-binding-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!