javascript - ng-repeat 中的条件 groupBy

标签 javascript angularjs angularjs-ng-repeat

如何在 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,因为我需要数据按其他变量(例如 )排序var2var3 等,并且不受 var1 分组的影响。

A fiddle供您展示两种想要的功能。

最佳答案

您可以设置 groupBy 来引用函数,并且在 Controller 中您可以执行自定义 groupBy 来检查如何分组的指示符。请参阅以下文档以获取更多信息。

http://ng-table.com/#/grouping/demo-api

这是一个应该展示这个概念的粗略尝试。

http://jsfiddle.net/wwgo4eo4/

//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/

相关文章:

javascript - Angular : How do I pass data between 2 views of a single page app?

javascript - Ng-repeat 根据所选单选答案隐藏单选按钮

javascript - 如何组合多个 getServerSideProps 包装器?

javascript - 在文本区域中模仿插入符号

javascript - 将绑定(bind)参数传递给 CSS

javascript - PositionError 网络位置提供程序位于 'https://www.googleapis.com/' : Returned error code 404

javascript - AngularJS - 如何访问对象中的数组以在 ng-bind 中使用

javascript - ng-repeat 中嵌套 ng-options - 如何被选中?

javascript - jquery 图像预览适用于 ajax 嵌入图像链接吗?

循环内的 JavaScript 闭包 – 简单的实际示例