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

时间:2019-02-28 15:33:22

标签: javascript angularjs angularjs-ng-repeat angular-ng-if

我的对象

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>

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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。 (例如您的示例)