【问题标题】:AngularJS: ngIf in array of array with different propertiesAngularJS:ngIf在具有不同属性的数组数组中
【发布时间】:2019-02-28 15:33:22
【问题描述】:

我的对象:

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-repeatng-if

<div class="row" ng-repeat="object in objects" ng-if="...???...">
  {{ object.name }}
  any text !!
</div>

【问题讨论】:

  • 你的数组不是数组而是对象数组。您能否澄清“具有不同属性”的含义?这是否意味着objects 中的元素可以有不同的结构?
  • @FlorianLim,对不起,我重新编辑我的帖子
  • 那么你为什么不把ng-if="object.foo.value &gt; 0 || object.foo.ignored == 1"放在主要的ngRepeat指令上呢?
  • @AlonEitan, foo 是一个数组
  • @sgrillon 哦,我没有看到那个编辑。 foo 可以包含多个对象,还是总是包含一个对象?

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


【解决方案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 

【讨论】:

    【解决方案2】:

    你可以这样做:

    <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。 (就像你的例子中的情况)

    【讨论】:

    • 抱歉,但在您的解决方案中object.name 显示多次。
    猜你喜欢
    • 2013-12-22
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多