ngIf用于遍历两个不同的数组

时间:2018-09-25 10:29:24

标签: angularjs angular-ng-if

我有这段代码:

<tr ng-repeat="row in someController.searchResults" 
    ng-class="{'selected': tableRow.selected}" 
    ng-click="selectRow(tableRow)" >

在这段代码中,我遍历searchResults数组。

我需要添加一个条件(想通过 ngIf 来做到)。

  • 如果条件为 true ,我将遍历someController.searchResults
  • 如果条件为 false ,我想遍历另一个数组,例如:someController.someOtherSearchResults

我该如何实现?

3 个答案:

答案 0 :(得分:0)

尝试一下

<div ng-if="Your condition(True)"> <tr ng-repeat="row in 
someController.searchResults" 
ng-class="{'selected': tableRow.selected}" 
ng-click="selectRow(tableRow)" >

<div ng-if="Your condition(False)"> <tr ng-repeat="row in 
someController.someOtherSearchResults" 
ng-class="{'selected': tableRow.selected}" 
ng-click="selectRow(tableRow)" >

希望这会对您有所帮助。

答案 1 :(得分:0)

请先过滤数据,然后再将数据传递给视图。

if(condition){
    this.results=searchResults;
    else{
    this.results=someOtherSearchResults;
    }

在模板中保持简单:

   <tr ng-repeat="row in someController.results" 
        ng-class="{'selected': tableRow.selected}" 
        ng-click="selectRow(tableRow)" >

OR

<tr ng-if="condition" ng-repeat="row in 
someController.searchResults" 
ng-class="{'selected': tableRow.selected}" 
ng-click="selectRow(tableRow)" >

<tr ng-if="!condition" ng-repeat="row in 
someController.someOtherSearchResults" 
ng-class="{'selected': tableRow.selected}" 
ng-click="selectRow(tableRow)" >

答案 2 :(得分:0)

您可以在ng-repeat属性中使用普通的javascript,如下所示:

<tr ng-repeat="row in (someController.importantBoolean ? someController.searchResults : someController.someOtherSearchResults)" 
        ng-class="{'selected': row.selected}" 
        ng-click="selectRow(row)" >
</tr>

有关示例,请参见以下示例:https://plnkr.co/edit/Nxh9gVB9GDP5FaLVDGrS