如何在AngularJS中处理循环中的if语句

how to deal with an if statement in a loop in AngularJS?

本文关键字:if 语句 循环 处理 AngularJS      更新时间:2023-09-26

我有两个循环

    <ion-list>
      <ion-item ng-repeat="category in categories" href="#">
        {{category.name}} {{category.id}}
          <ion-item ng-repeat="test in tests" href="#">
              {{test.name}} {{test.cat_id}}
          </ion-item>
      </ion-item>
    </ion-list>

我想测试if(category.id === test.cat_id),然后显示第二个列表

我不确定是否以及如何使用ngif,或者我是否应该在控制器中处理这个问题,并返回一个已经根据我的需要格式化的对象。。

有什么想法吗?

如果我理解正确,您希望有条件地显示第二个ng重复。如果是这样的话,那么你可以使用这个:

<ion-list>
  <ion-item ng-repeat="category in categories" href="#">
    {{category.name}} {{category.id}}
      <ion-item ng-repeat="test in tests" href="#" ng-if="category.id === test.cat_id">
          {{test.name}} {{test.cat_id}}
      </ion-item>
  </ion-item>
</ion-list>

另一种选择是使用这样的过滤器:

<ion-list>
  <ion-item ng-repeat="category in categories" href="#">
    {{category.name}} {{category.id}}
      <ion-item ng-repeat="test in tests | filter: {cat_id: category.id}" href="#" ng-if="category.id === test.cat_id">
          {{test.name}} {{test.cat_id}}
      </ion-item>
  </ion-item>
</ion-list>

实际上,我会推荐过滤器选项。

这样的东西怎么样?

<ion-list>
  <ion-item ng-repeat="category in categories" href="#">
    {{category.name}} {{category.id}}
      <ion-item ng-repeat="test in tests | filter:{cat_id: category.id}" href="#">
          {{test.name}} {{test.cat_id}}
      </ion-item>
  </ion-item>
</ion-list>