AngularJS Group By Directive without External Dependencies

前端 未结 9 994
长发绾君心
长发绾君心 2020-11-29 01:01

I\'m new to Angular and would like to learn the best way to handle a problem. My goal is to have a reusable means to create group by headers. I created a solution which wor

9条回答
  •  广开言路
    2020-11-29 01:13

    Below is a directive-based solution, as well as a link to a JSFiddle demoing it. The directive allows each instance to specify the field name of the items it should group by, so there is an example using two different fields. It has linear run-time in the number of items.

    JSFiddle

    Grouping by FirstFieldName

    Grouping by SecondFieldName

    angular.module('myApp', []).directive('groupWithHeaders', function() { return { template: "
    " + "

    {{group}}

    " + "
    " + "{{item.whatever}}" + "
    " + "
    ", scope: true, link: function(scope, element, attrs) { var to_group = scope.$eval(attrs.toGroup); scope.groups = {}; for (var i = 0; i < to_group.length; i++) { var group = to_group[i][attrs.groupBy]; if (group) { if (scope.groups[group]) { scope.groups[group].push(to_group[i]); } else { scope.groups[group] = [to_group[i]]; } } } } }; }); function TestGroupingCtlr($scope) { $scope.MyList = [ {FirstFieldName:'Group 1', SecondFieldName:'Group a', whatever:'abc'}, {FirstFieldName:'Group 1', SecondFieldName:'Group b', whatever:'def'}, {FirstFieldName:'Group 2', SecondFieldName:'Group c', whatever:'ghi'}, {FirstFieldName:'Group 2', SecondFieldName:'Group a', whatever:'jkl'}, {FirstFieldName:'Group 2', SecondFieldName:'Group b', whatever:'mno'} ]; }

提交回复
热议问题