Javascript Knockout.js foreach:但仅当比较为真时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8869264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout.js foreach: but only when comparison is true
提问by LouwHopley
How can I control the foreach to ignore certain elements by using a comparison?
如何通过比较控制 foreach 忽略某些元素?
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.
所以我希望它做的是循环遍历entry
's 但仅在该电流entry
的number
值大于 10时才执行。
Is this possible to do?
这是可能的吗?
回答by Bj?rn Kaiser
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.
目前,knockout.js 无法做到这一点,但这是一个有趣的功能。您应该提交错误报告/联系作者以考虑将其用于未来版本。
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
.
方式 2:
编写一个自定义过滤器方法,该方法为您提供一组与您的条件匹配的元素,并在您的foreach
.
回答by JustMe
try this:
尝试这个:
<div data-bind="foreach: editingItem.columns">
<!-- ko if: Selected-->
<div data-bind="text: Name"></div>
<input type="text"/>
<!-- /ko -->
回答by Simon
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)
我认为最好使用内置的 arrayFilter 方法(参见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
然后你可以像往常一样将数据绑定到filteredEntries
回答by kernowcode
What about
关于什么
<div data-bind="foreach: _.filter(entry(), function(item) { return item.number > 10;})">
using underscore.js
使用 underscore.js
回答by Ali Karaca
You can use array.filterfunction to filter the array, Don't forget to pass "this"
您可以使用array.filter函数来过滤数组,不要忘记传递“this”
<div data-bind="foreach: yourArrayHere.filter(function(entry){return entry.number > 10}, this)">