Search code examples
angularjsangular-filters

Count group elements using angular-filter


Is it possible using angular-filter "groupBy" (https://github.com/a8m/angular-filter#groupby) to count the elements in each group to use in a "badge" span (of course without using a a function doing the "manual count")

<div class="list-group" ng-repeat="(key, value) in directoryResult | groupBy: 'TableId'">
    <a href="#" class="list-group-item active">
        <span class="glyphicon glyphicon-transport"></span> {{convertTableid(key)}} <span class="badge">{{directoryResult.length}}</span>
    </a>
    <div class="list-group" ng-repeat="item in value">
        <a href="#" class="list-group-item">
            <span class="glyphicon glyphicon-transport"></span> {{item.Text}}
        </a>
    </div>
</div>

Solution

  • If you do something like:

    ng-repeat="(key, value) in directoryResult | groupBy: 'TableId' as result"
    

    then result will be the filtered variable. You can check the length of that for the number of groups.

    Update:

    Here is a plunker with a groupBy filter.
    http://plnkr.co/edit/8jB4wSRtKfVmEsTGZtfV?p=preview

    I took an existing filter I found (since angular doesn't have a built in one) and added a length property. The results show up properly.

    Update 2:
    Another plunker:
    http://plnkr.co/edit/iwUkIMjvevja7KyfTrFC?p=preview

    Since angular-filter doesn't provide a length property, you have to count it yourself with Object.keys

    <div>Number of groups: {{numGroups(result) }} </div>
    

    JS:

    $scope.numGroups = function(input){
        return Object.keys(input).length;
    }
    

    Update 3: the result contains an object literal: each property is named "key" and its value is a subgroup of the list. So the running solution is:

    <div>Number of groups: {{numGroups(result[key]) }} </div>
    

    Update 4 Finally we may get rid completly of the numGroups function, using directly:

    <div>Number of groups: {{result[key].length}} </div>
    

    So your first idea was the good one, I had just to adapt it as my groupBy resturn an object literal containing all the goruped lists.