dmathisen
dmathisen

Reputation: 2342

Knockout JS foreach data-binding and nesting element

I have a list that I'd like to produce a link containing an icon and text:

<li><a><img src="icon.png" /> name</a></li>

So ideally the setup would look like:

<ul data-bind="foreach: list">
    <li>
        <a data-bind="text: name, click: openNavItem"><img data-bind="attr: { src: icon }" /></a>
    </li>
</ul>

Then I'm passing:

list.push({ name: "name", icon: "theicon.png" });

JS Fiddle example

This doesn't work because the 'a data-bind="text: name, ..."' overwrites the image.

Does that make sense? Is there a good way to accomplish this?

Upvotes: 2

Views: 904

Answers (2)

HungryCoder
HungryCoder

Reputation: 7616

You can use knockout's container less syntax to achieve this.

<ul data-bind="foreach: list">
    <li>
        <a><img data-bind="attr: { src: icon }" />
        <!--ko text: name--><!--/ko-->
        </a>
    </li>
</ul>

Upvotes: 2

Dmitry S.
Dmitry S.

Reputation: 8503

What about defining a link like this?

<a href="#"><img data-bind="attr: { src: icon }" /><span data-bind="text: name" /></a>

Upvotes: 3

Related Questions