AngularJS:具有不同属性的数组数组中的ngIf

问题描述 投票:0回答:2

我的目标:

objects = [
{
    name: "1",
    foo: [{
      value: 0.5,
      ignored: null,
      text: "foo1"
    }, {
      value: 0,
      ignored: null,
      text: "foo"
    }]
},
{
    name: "2",
    foo: [{
      value: 0,
      ignored: null,
      text: "foo"
    }, {
      value: 0.5,
      ignored: null,
      text: "foo2"
    }]
},
{
    name: "3",
    foo: [{
      value: 0.5,
      ignored: null,
      text: "foo3"
    }]
},
{
    name: "4",
    foo: [{
      value: 0,
      ignored: 1,
      text: "foo4"
    }]
},
{
    name: "5",
    foo: [{
      value: 0,
      ignored: null,
      text: "foo5"
    }]
}]

我的AngularJs模板html:

<div class="row" ng-repeat="object in objects">
  {{ object.name }}
  <div ng-repeat="foo in object.foo">
    <div ng-if="foo.value > 0 || foo.ignored == 1">
      {{ foo.text }}
    </div>
  </div>
</div>

我的结果是:

1 foo1
2 foo2
3 foo3
4 foo4
5

但我不希望在N°5的情况下显示object.name

如何在第一个ng-repeat使用第二个ng-ifng-repeat好吗?

<div class="row" ng-repeat="object in objects" ng-if="...???...">
  {{ object.name }}
  any text !!
</div>
javascript angularjs angularjs-ng-repeat angular-ng-if
2个回答
1
投票

您可以在ng-if中使用过滤器功能。

更改模板:

<div class="row" ng-repeat="object in objects" ng-if="myFilter(object)">
  {{ object.name }}
  <div ng-repeat="foo in object.foo">
    <div ng-if="foo.value > 0 || foo.ignored == 1">
      {{ foo.text }}
    </div>
  </div>
</div>

控制器中的过滤功能:

$scope.myFilter = function(o) {
  // Returns a truthy value if the foo-subarray meets the criteria.
  var found = o.foo.find(function(fooElement) {
    return fooElement.value > 0 || fooElement.ignored == 1;
  });
  return found;
};

结果:

1
foo1
2
foo2
3
foo3
4
foo4 

0
投票

你可以这样做:

<div class="row" ng-repeat="object in objects">
  <div ng-repeat="foo in object.foo">
    <div ng-if="foo.value > 0 || foo.ignored == 1">
      {{ object.name }}
      {{ foo.text }}
    </div>
  </div>
</div>

如果事先知道object.foo中只有一个元素可以传递ngIf。 (就像你的例子中的情况一样)

© www.soinside.com 2019 - 2024. All rights reserved.