user1532573
user1532573

Reputation: 81

Knockout foreach is not creating child elements

The binding below works in that it creates the li and a elements as expected, but for some reason the i element nested inside the a element is not created. How do I tell knockout to create nested i element?

The fiddle: http://jsfiddle.net/TJdhW/3/ illustrates this. The li items are created without icons.

<script>
    $(function () {
        var item = function (p) {
            self = this;
            self.property = ko.observable(p);
        }
        var data = ko.observableArray([]);

        var test = new item("one");


        data().push(new item("one"));
        data().push(new item("two"));
        data().push(new item("three"));

        var vm = {
            data : data
        }


        ko.applyBindings(vm);
    });
</script>


<ul class="nav nav-tabs">
    <li><a href="#home" data-toggle="tab" style="background-color: maroon;">ePM</a></li>
    <li><a href="#home" data-toggle="tab"><i class="icon-list"></i></a></li>
    <li><a href="#home" data-toggle="tab"><i class="icon-bar-chart"></i></a></li>

    <!-- ko foreach: data-->
    <li><a href="#home" data-toggle="tab" data-bind="text: property"><i class="icon-list" style="margin-right: 2px"></i></a></li>
    <!-- /ko -->

    <li><a href="#home" data-toggle="tab"><i class="icon-list" style="margin-right: 1px;"></i><i class="icon-plus"></i></a></li>
    <li><a href="#home" data-toggle="tab"><i class="icon-bar-chart" style="margin-right: 1px;"></i><i class="icon-plus"></i></a></li>
</ul>

http://jsfiddle.net/TJdhW/3/

Upvotes: 1

Views: 229

Answers (1)

nemesv
nemesv

Reputation: 139748

The problem is with your data-bind="text: property" an the a element which replaces the whole content of the link so it removes the icon and only displays the value of the property property.

In order to have both the text and the icon inside your anchor move the data-bind="text: property" inside the a (for example on a span element):

 <!-- ko foreach: data-->
        <li><a href="#home" data-toggle="tab" >
            <span data-bind="text: property"></span>
            <i class="icon-list" style="margin-right: 2px" ></i>
            </a>
        </li>
 <!-- /ko -->

Demo JSFiddle.

Upvotes: 2

Related Questions