1

I have an existing knockout foreach like so:

<!-- ko foreach: reportFields -->
<tr>
   <td><span class="hover" data-bind="text: FriendlyName, click:$parent.openField"></span></td>
   <td><img src="img/cross.png" data-bind="click: $parent.removeField" class="delete" alt="Remove Field" title="Remove Field" /></td>
</tr>
<!-- /ko --> 

What I need to do is filter the foreach further i.e. I want to check a field of each item to see if it equals 1, 2 or 3. I tried simply putting a knockout if statement directly after the ko foreach but it fails to work unless I put it after some html code which is a problem as I don't want to show anything unless it matches.

So my question is can I filter the ko foreach in some way with a where statement or something similar, or is there a way to get the if statement functioning without needing to have html before declaring it?

4

2 に答える 2

4

要素にifバインディングを追加できます:tr

<!-- ko foreach: reportFields -->
<tr data-bind="if: SomeField() == 1">
   <td><span class="hover" data-bind="text: FriendlyName, click:$parent.openField"></span></td>
   <td><img src="img/cross.png" data-bind="click: $parent.removeField" class="delete" alt="Remove Field" title="Remove Field" /></td>
</tr>
<!-- /ko --> 

computed valueまたは、 に保存filtered arrayして使用するイン ビュー モデルを作成できますforeach

self.filteredItems = ko.computed(function() {
        return ko.utils.arrayFilter(self.reportFields(), function(item) {
            return item.someField() == 1;
        });

});
于 2012-10-29T10:13:51.350 に答える
0

計算された観測可能な配列を使用できます。

function ReportViewModel() {
  this.reportFields = ko.observableArray(...);
  this.reportFilter = ko.observable();  // bind to dropdown with values 1, 2 or 3

  this.reportFieldsFiltered = ko.computed(function () {
    var filterValue = this.reportFilter();

    return ko.util.arrayFilter(this.reportFields(), function (item) {
      return item.property() == filterValue;
    });
  }, this);
}

そして使用する

<!-- ko foreach: reportFieldsFiltered -->
<tr>
   <td><span class="hover" data-bind="text: FriendlyName, click:$parent.openField"></span></td>
   <td><img src="img/cross.png" data-bind="click: $parent.removeField" class="delete" alt="Remove Field" title="Remove Field" /></td>
</tr>
<!-- /ko --> 

ちなみに、<tbody data-bind="foreach: reportFieldsFiltered">仮想要素の代わりに使用できます。

于 2012-10-29T10:15:16.330 に答える