Knockout.js foreach: but only when comparison is t

2019-03-17 14:15发布

How can I control the foreach to ignore certain elements by using a comparison?

What I want for example is something like this:

<div data-bind="foreach: entry where (entry.number > 10)">

So what I would want it to do is loop through entry's but only execute when that current entry has a number value of more than 10.

Is this possible to do?

4条回答
在下西门庆
2楼-- · 2019-03-17 14:38

try this:

   <div data-bind="foreach: editingItem.columns">
         <!-- ko if: Selected-->
         <div data-bind="text: Name"></div>
          <input type="text"/>
             <!-- /ko -->
查看更多
男人必须洒脱
3楼-- · 2019-03-17 14:45

Currently that's not possible with knockout.js, but it's an interesting feature. You should file a bug report/contact the author to consider it for a future version.

Way 1:

<div data-bind="foreach: entry">
     <div data-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.

查看更多
该账号已被封号
4楼-- · 2019-03-17 14:51

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

查看更多
霸刀☆藐视天下
5楼-- · 2019-03-17 14:51

What about

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

using underscore.js

查看更多
登录 后发表回答