AngularJS Group By Directive without External Dependencies

前端 未结 9 984
长发绾君心
长发绾君心 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:28

    EDIT: here's a custom filter approach. Groups is created by a filter function in scope to generate array of groups from current list. Adding/deleting list items will bind update of the group array as it is reset every digest cycle.

    HTML

    {{group}}

    • {{item.whatever}}

    JS

    var app=angular.module('myApp',[]);
    app.filter('groupby', function(){
        return function(items,group){       
           return items.filter(function(element, index, array) {
                return element.GroupByFieldName==group;
            });        
        }        
    })        
    
    app.controller('TestGroupingCtlr',function($scope) {
    
        $scope.MyList = [{  GroupByFieldName: 'Group 1', whatever: 'abc'},
                         {GroupByFieldName: 'Group 1',whatever: 'def'}, 
                         {GroupByFieldName: 'Group 2',whatever: 'ghi' },
                         {GroupByFieldName: 'Group 2',whatever: 'jkl'}, 
                         {GroupByFieldName: 'Group 2',whatever: 'mno'  }
                        ];
        $scope.getGroups = function () {
            var groupArray = [];
            angular.forEach($scope.MyList, function (item, idx) {
                if (groupArray.indexOf(item.GroupByFieldName) == -1)
                  groupArray.push(item.GroupByFieldName)
            });
            return groupArray.sort();
        }
    
    })
    

    DEMO

提交回复
热议问题