Reputation: 946
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.
Upvotes: 5
Views: 3745
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
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
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