我使用Angular和Bootstrap表示数据网格,并向用户提供对其的一些控制(编辑数据等)。数据集是对象数组,每个对象都有一个group属性,该属性不是唯一的,代表记录所引用的组。

因此,数据集看起来像

[
  {
    id: 1,
    group: 'A',
    value: 'John'
  }, {
    id: 2,
    group: 'A',
    value: 'Jake'
  }, {
    id: 3,
    group: 'B',
    value: 'Jack'
  }
]


我想要Angular输出

<div class="row group">
  <div class="col-md-12">A</div>
</div>
<div class="row sample">
  <div class="col-md-4">1</div>
  <div class="col-md-8">John
<div>
...


我尝试了ng-repeat,但是它只允许将数组折叠成另一个,因此,{{ group }}将是顶部元素,而{{ elementOfAGroup }}将是其子元素。我需要最终的标记才能成为一组简单的DOM元素。

我用谷歌搜索了一个解决方案,但我发现的唯一是可以组成表格的简单组件(指令)。

最佳答案

我使用自定义“ uniq”过滤器来完成此任务:



<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.1.1/angular-filter.js"></script>
    </head>
    <body ng-app="plunker" ng-controller="MainCtrl">
        <div class="row group" ng-repeat="data in dataset | uniq: 'group'">
            <h3>{{data.group}}</h3>
            <div class="col-md-12" ng-repeat="child in dataset | filter: { group: data.group }">{{child.value}}</div>
        </div>
    </body>
    <script>
        var app = angular.module('plunker', ['angular.filter']);

        app.controller('MainCtrl', ['$scope', '$sce', function($scope, $sce) {
            $scope.dataset = [
                {
                    id: 1,
                    group: 'A',
                    value: 'John'
                }, {
                    id: 2,
                    group: 'A',
                    value: 'Jake'
                }, {
                    id: 3,
                    group: 'B',
                    value: 'Jack'
                }
            ];

        }]);
    </script>
</html>





使用大数据集可能会很慢。

关于javascript - 使用Angular将一维列表中的数据分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26118604/

10-11 19:48
查看更多