Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout data-binding nested html elements

Tags:

knockout.js

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/

like image 487
HashCoder Avatar asked Apr 26 '12 08:04

HashCoder


People also ask

How do I use KnockoutJS in HTML?

It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in HTML pages. A page as in the following image will be displayed. Click on download link and you will get the latest knockout.

What is data binding in HTML?

A data binding connects data from a custom element (the host element) to a property or attribute of an element in its local DOM (the child or target element). The host element data can be a property or sub-property represented by a data path, or data generated based on one or more paths.

What is data bind Knockout?

Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding.


2 Answers

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>
like image 120
Manatherin Avatar answered Sep 28 '22 08:09

Manatherin


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/

like image 36
RP Niemeyer Avatar answered Sep 28 '22 07:09

RP Niemeyer