vegemite4me
vegemite4me

Reputation: 6856

Knockout containerless control flow syntax not executing data bindings

I am trying to use Knockout's containerless control flow syntax without much luck. Well, the actual control flow is working, but child HTML elements are not getting bound.

I have a simple object:

function Person(name, vegetarian) {
    var self = this;
    self.name = name;
    self.vegetarian= vegetarian;
}

And I want a list of all people, with a link to the Vegetarian society if they are vegetarian.

<ul data-bind="foreach: people">
<li>
        <!-- ko if: vegetarian() -->
        <a href="http://www.vegsoc.org">
        <!-- /ko -->
        <span data-bind="text: name"></span>
        <!-- ko if: vegetarian() -->
        </a>
        <!-- /ko -->
    </li>
</ul>

http://jsfiddle.net/mxmS9/

Why are my 2 people not getting displayed in the list?

Delete the ko comments and you will at least see that the foreach is working correctly.

I am using the containerless control flow syntax because in my actual project, there is a lot more HTML than the simple <span> in this example, and I do not want to repeat it.

Knockout v2.3.0

Upvotes: 3

Views: 3694

Answers (1)

nemesv
nemesv

Reputation: 139768

You cannot use the containerless control flow syntax this way, because you cannot break up a n element's open/closing tags with them.

What you need to do is to repeat the common content:

<ul data-bind="foreach: people">
    <li>
        <!-- ko if: vegetarian -->
        <a href="http://www.vegsoc.org"><span data-bind="text: name"></span></a>
        <!-- /ko -->
        <!-- ko ifnot: vegetarian -->
            <span data-bind="text: name"></span>
        <!-- /ko -->
    </li>
</ul>

Or if you have more content what you don't want to repeat move it to a template:

<ul data-bind="foreach: people">
    <li>
        <!-- ko if: vegetarian -->
        <a href="http://www.vegsoc.org" data-bind="template: 'linkTemplate'"></a>
        <!-- /ko -->
        <!-- ko ifnot: vegetarian -->
            <!-- ko template: 'linkTemplate'--><!-- /ko -->
        <!-- /ko -->
    </li>
</ul>
<script type="text/html" id="linkTemplate">
  <span data-bind="text: name"></span>
</script>

Demo JSFiddle.

Upvotes: 5

Related Questions