Skip to content Skip to sidebar Skip to footer

Knockout.js Foreach: But Only When Comparison Is True

How can I control the foreach to ignore certain elements by using a comparison? What I want for example is something like this:

Way 1:

<divdata-bind="foreach: entry"><divdata-bind="if: entry.number > 10"></div></div>

Way 2: Write a custom filter method that gives you an array of elements that match your conditions and use this in your foreach.

Solution 2:

try this:

<divdata-bind="foreach: editingItem.columns"><!-- ko if: Selected--><divdata-bind="text: Name"></div><inputtype="text"/><!-- /ko -->

Solution 3:

I think it would be better to use the built in arrayFilter method ( see http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html )

viewModel.filteredEntries = ko.computed(function() {

    return ko.utils.arrayFilter(this.entries(), function(item) {
        return item.number > 10;
    });

}, viewModel);

Then you can just databind to the filteredEntries as you would normally

Solution 4:

What about

<div data-bind="foreach: _.filter(entry(), function(item) { return item.number > 10;})">

using underscore.js

Solution 5:

You can use array.filter function to filter the array, Don't forget to pass "this"

<div data-bind="foreach: yourArrayHere.filter(function(entry){return entry.number > 10}, this)">

Post a Comment for "Knockout.js Foreach: But Only When Comparison Is True"