简体   繁体   中英

Knockout binding with nested html elements

I have some issues with knockout bindings when using nested html elements as below

<ul class="result-list" data-bind="foreach: newsData">
    <li>
        <a class="big-link" data-bind="text: Title, attr: { href: Url }"></a>
        <div data-bind="html: Content"></div>
        <div class="meta" data-bind="text: PublishDate">
            <span class="time" data-bind="text: PublishTime"></span>
            <span class="changed" data-bind="text: ChangedDate, visible: IsChanged">
                <span class="time" data-bind="text: ChangedTime"></span>
            </span>
        </div>
    </li>
</ul>

The json

var sample = [{
    "Id": 80055,
    "Title": "Not changed!",
    "Content": "<p>Curabitur eget euismod mi. Cras mollis augue a massa porttitor posuere. Quisque tempus justo vel orci venenatis lobortis.</p>",
    "Url": "/asd/Not-changed/",
    "PublishDate": "28. mars 2014",
    "PublishTime": "Kl 01:30",
    "IsChanged": false,
    "ChangedDate": "28. mars 2014",
    "ChangedTime": "Kl 01:30"
}, {
    "Id": 80046,
    "Title": "Ny artikkel",
    "Content": "<p>This is content</p>\n<p>Demo</p>",
    "Url": "/asd/Ny-artikkel/",
    "PublishDate": "4. mars 2014",
    "PublishTime": "Kl 12:00",
    "IsChanged": true,
    "ChangedDate": "24. mars 2014",
    "ChangedTime": "Kl 04:47"
}];

It binds well down to the PublishDate but that seem to overwrite all child elements. Any advice how to solve this?

Reading from the Knockout docs for the text binding:

Knockout sets the element's content to a text node with your parameter value. Any previous content will be overwritten

You might need to write sub-elements to house those data bindings:

<ul class="result-list" data-bind="foreach: newsData">
    <li>
        <a class="big-link" data-bind="text: Title, attr: { href: Url }"></a>
        <div data-bind="html: Content"></div>
        <div class="meta">
            <span data-bind="text: PublishDate"></span>
            <span class="time" data-bind="text: PublishTime"></span>
            <span class="changed">
                <span data-bind="text: ChangedDate, visible: IsChanged"></span>
                <span class="time" data-bind="text: ChangedTime"></span>
            </span>
        </div>
    </li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM