【问题标题】:Can 'if' be used in conjunction with 'foreach' within 'template' binding Knockout'if' 可以在 'template' 绑定 Knockout 中与 'foreach' 一起使用
【发布时间】:2016-03-19 05:38:20
【问题描述】:

我正在使用敲除模板将可观察数组绑定到视图。我有一个对象数组,但我只想显示满足特定条件的对象。无论如何使用淘汰模板绑定来做到这一点?我目前正在使用提出的第二种解决方案(可行),因为第一种会导致错误,但我觉得可能有更简洁的方法来做到这一点。

期望的解决方案(产品未定义的错误):

<div class="productItem" data-bind="template: { name: 'product-template',foreach:'history', as:'product', if: product.Count === 1}"></div>

我的解决方法:

<!-- ko foreach: { data: history, as: 'product' } -->
<div class="productItem" data-bind="template: { name: 'product-template', if: product.Count === 1}"></div>
<!-- /ko -->

【问题讨论】:

  • 您至少应该将"history" 的双引号替换为单引号。此外,我确定您不能将 foreachif 组合在一个绑定中。

标签: javascript knockout.js


【解决方案1】:

我无法在一个语句中找到一种简洁的方法,但也许您可以将 if 逻辑移到模板本身中?

<ul data-bind="template: {name:'template', foreach: items}">

</ul>
<script type="text/html" id="template">
  <!-- ko if: show -->
    <li>
    <span data-bind="text: name"></span>
  </li>
  <!-- /ko -->
</script>

在此处查看完整示例:http://jsfiddle.net/nheu9uvq/1/

【讨论】:

  • 这个问题是我希望能够显示不同版本的列表(基于元素的属性)。此解决方案将要求我为要显示的列表的每个不同版本(使用不同的“if”绑定)创建多个几乎相同的模板。
  • 您可以将要检查的字段作为要检查的参数传递给模板
【解决方案2】:

使用computed 根据其Count 成员过滤history。或基于任意成员进行过滤的函数。

【讨论】:

    【解决方案3】:

    模板绑​​定本身支持if 参数。

    它在文档中。 http://knockoutjs.com/documentation/template-binding.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-03
      • 2014-08-22
      • 2013-07-18
      • 2017-06-10
      • 2021-07-04
      • 2012-09-24
      • 2014-03-28
      • 1970-01-01
      相关资源
      最近更新 更多