HashCoder
HashCoder

Reputation: 946

Knockout data-binding nested html elements

I have h2 tag with data-bind text property to a model value and inside i have a span tag which is also a data-bind text property to a model value.

But span is getting replace when the model is binded, is there any way to append the html.

http://jsfiddle.net/WKnWr/1/

Upvotes: 5

Views: 3745

Answers (3)

Manatherin
Manatherin

Reputation: 4187

With the newest knockout you could use a virtual element for the h2 text, similar to John Earles solution but it means that you could style the last name separately to the first name

<h2>
    <!-- ko text: firstName --><!-- /ko --> 
    <span data-bind="text: lastName"></span>
</h2>

Upvotes: 9

RP Niemeyer
RP Niemeyer

Reputation: 114792

Normally, you would want to change your HTML to work properly for this scenario. However, if that is not possible, then you could use a custom binding that inserts the span for you.

It would be like:

ko.bindingHandlers.insertText = {
    init: function(element, valueAccessor) {
        var span = document.createElement("span"),
            firstChild = element.firstChild;

        element.insertBefore(span, firstChild);
        ko.applyBindingsToNode(span, { text: valueAccessor() });       
    }       
};

Sample: http://jsfiddle.net/rniemeyer/fLmXu/

Upvotes: 3

John Earles
John Earles

Reputation: 7194

Your current code will overwrite because the 'text' binding sets the innerText (or textContent) for that element, so your h2 text binding will overwrite any existing embedded html (such as your span).

You could do this:

<h2>
    <span data-bind="text:firstName"></span>
    <span data-bind="text:lastName "></span>
</h2>​

Upvotes: 3

Related Questions