Lydon
Lydon

Reputation: 2975

Using angularjs filter and _.groupBy

Here's a simple example I created to replicate my issue. In my controller, I have an array of people:

$scope.people = [
    { name: 'fred', age: 20 },
    { name: 'bob', age: 22 },
    { name: 'jane', age: 24 },
    { name: 'mary', age: 22 },
    { name: 'ben', age: 24 },
    { name: 'sarah', age: 21 },
];

I have a filter defined:

.filter('grouped', function () {
    return function (input) {
        return _.groupBy(input, 'age');
    }
})

You may notice that I'm using Lo-Dash to do the group by.

In my view I have a list defined:

<div class="list" ng-repeat="personGroup in people | grouped">
    {{ $index }}
    <div class="list" ng-repeat="person in personGroup">
        {{ person.name }}
    </div>
</div>

I get the result I'm after but I get a heap of errors in my developer console.

https://docs.angularjs.org/error/$rootScope/infdig?p0=10

I understand why I'm getting the error. This is explained in detail in the above link. I just don't know the proper way of achieving the result I'm after.

Upvotes: 2

Views: 3813

Answers (2)

GonchuB
GonchuB

Reputation: 705

What version of angular are you using? I'm not getting any error:

http://plnkr.co/edit/bbDGjHWMGZx5GmNcggaw?p=preview

Upvotes: 0

Nikolas
Nikolas

Reputation: 1176

As you are creating new Array-objects when grouping the people, I would not use a filter at all. The easiest solution would be to do the grouping inside your controller:

...
$scope.groups = _.groupBy($scope.people, 'age');
...

Your ng-repeat attribute would then read like:

ng-repeat="personGroup in groups"

Upvotes: 2

Related Questions