如何在 Angular ng-repeat
指令中应用条件分组?
例如,在下面的代码中,我想要 groupBy:'var1'
,但仅当某些变量或表达式 dontGroup
计算结果为 true 时。我不想在 HTML 中专门为 dontGroup
变量复制底部的 tr
行,因为无法通过模板加载第二个 的信息tr
由于主表由指令控制,并且在初始化之前需要 DOM 中的模板。如果有一种方法可以做到这一点,但我忽略了,请告诉我。我正在使用 ng-table
。
<table>
<tr ng-repeat-start="(key, data) in $data | groupBy:'var1'">
<td ng-bind="key">
<!-- Grouped header info here. -->
</td>
</tr>
<tr ng-repeat-end ng-repeat="item in data"> <!-- Repeat $data when `dontGroup` evaluates to true,
otherwise repeat pre-grouped data from the `groupBy` filter above -->
<td ng-bind="item.var2">
<!-- Individual item info here. -->
</td>
</tr>
</table>
因此,我希望较低的 ng-repeat
函数仅在 dontGroup
时将 $data
重复为 data
计算结果为 true,但否则我希望通过 groupBy
过滤器运行 $data
,以便数据可以具有该组的 header 。
当 dontGroup
计算结果为 true 时,我也不能在标题行上放置 ng-if
,因为我需要数据按其他变量(例如 )排序var2
、var3
等,并且不受 var1
分组的影响。
A fiddle供您展示两种想要的功能。
最佳答案
您可以设置 groupBy 来引用函数,并且在 Controller 中您可以执行自定义 groupBy 来检查如何分组的指示符。请参阅以下文档以获取更多信息。
http://ng-table.com/#/grouping/demo-api
这是一个应该展示这个概念的粗略尝试。
//template
<input type="checkbox" ng-click="clickGroupBY()"/>
<table>
<tr ng-repeat-start="(key, data) in $data | groupBy:valueGroupBY">
//controller
$scope.willgroupby = true;
$scope.valueGroupBY = function(group) {
if($scope.willgroupby) {
return group.var1
}
return group.var2
}
$scope.clickGroupBY = function clickGroupBY() {
$scope.willgroupby = !$scope.willgroupby;
}
更新
我运行了您返回的解决方案 here并把它清理干净。请参阅以下内容:http://jsfiddle.net/r1mss7s0/1/
我还发现这可以提供有关您正在使用的过滤器的信息: https://github.com/a8m/angular-filter/wiki/Common-Questions
关于javascript - ng-repeat 中的条件 groupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42121106/