Span tag inside Anchor tag for data-bind

816 views
Skip to first unread message

surya...@gmail.com

unread,
Sep 26, 2012, 6:58:12 AM9/26/12
to knock...@googlegroups.com
Hi Team,

If i have a span tag inside a anchor tag how do i achieve it as mentioned below including class names

 <a class="available-media" href="#" data-bind="text: firstName">
<span class="spanClass" data-bind="text: lastName"></span> 
                    </a>

Please help me in this regard.

Michael Best

unread,
Sep 26, 2012, 7:38:52 AM9/26/12
to knock...@googlegroups.com, surya...@gmail.com
The text binding replaces any contents of the element with the text provided. So it wiped out the span tag. You need to do it like this:

<a class="available-media" href="#">
<span class="spanClass" data-bind="text: firstName"></span>  
<span class="spanClass" data-bind="text: lastName"></span> 
</a>

hroerdi...@gmail.com

unread,
Sep 26, 2012, 8:46:19 AM9/26/12
to knock...@googlegroups.com, surya...@gmail.com
Just to prevent an alternative, you could make a custom binding:

var viewModel = {
    firstName: ko.observable('John'),
    lastName: ko.observable('Doe')
}

viewModel.fullName = ko.computed(function () {
    return this.firstName() + ' ' + this.lastName();
}, viewModel);

and solve it as such:

<a class="available-media" href="#">
<span class="spanClass" data-bind="text: fullName"></span> 
</a>

hroerdi...@gmail.com

unread,
Sep 29, 2012, 5:08:15 AM9/29/12
to knock...@googlegroups.com, surya...@gmail.com
Hi Surya,

I got an email with a reply from you in the mail. I don't see the reply here, but I'll try to answer it anyway. I realized from your reply we didn't look closely enough at your problem. However, the fix is extremely small. By itself, a span-tag doesn't do much, and it's ideal for solving problems such as these. This is how I ended up doing it:

http://jsfiddle.net/PyK4A/2/

The only difference from before is that the first span-tag inside the anchor-tag does not have a class anymore. Consequently, it will adopt the styling from the anchor-tag, since a span-tag, as I said, by itself shouldn't do much (unless you give it a specific class that does stuff). This type of fix, by introducing an extra span to prevent other content from being wiped by your text-binding in the anchor-tag, is a common pattern with Knockout. So if you don't understand it, just ask and I'll explain it better.

About your second problem, selecting the boxes, you didn't fully specify the behavior you wanted (one or two questions left open). Is this what you want?

http://jsfiddle.net/ugkqd/31/


Reply all
Reply to author
Forward
0 new messages