user736893
user736893

Reputation:

Knockout foreach only display if property = value?

I originally had something like the following:

<span data-bind="foreach: objects">
    <span data-bind="if: object.type() === 'menuItem'>
       ...
    </span>
</span>

This technically worked, but it actually created a DOM element for EVERY object, regardless of type, but the matching ones were the only ones "populated". It left slight gaps in the UI.

I switched to using a virtual element, which works much better, but still shows up in the DOM as

<!-- ko if: object.type() === 'menuItem'>
<!-- /ko -->

for all the nonmatching elements.

Is there a way to embed the if statement in the original foreach or would it be better to do this logic in the viewmodel somehow?

Upvotes: 0

Views: 268

Answers (1)

PW Kad
PW Kad

Reputation: 14995

You cannot embed an if in the same element as a foreach because they are trying to control the same descendant binding, which is the error that Knockout will give you when you try.

http://jsfiddle.net/h92LY/

The use of a containerless binding is 100% the correct direction to go. Another option is using a computed where the condition is inside of it, but that is taking presentation logic into the view model -

view model -

var showingObjects= ko.computed(function () {
    return ko.utils.arrayFilter(objects(), function(object) {
        return object.type() === 'menuItem';
    });
});

view -

<span data-bind="foreach: showingObjects">
       ...
</span>

Upvotes: 2

Related Questions