Kathir
Kathir

Reputation: 6196

Angular group by and filter

I am trying to group my collection based on a property and at the same time i would like to filter my collection with one property.

When i try the following,

 <div data-ng-repeat="(group,parameter) in parameters | filter : { 'type' : '!GroupType' }| groupBy :'group'">
                        <fieldset>
                            <legend>{{group}}</legend>
                            <div data-ng-repeat="par in parameter">
                                <myfield ng-model="par.value" parameter="par" entry-map="entryMap"></myfield>
                            </div>
                        </fieldset>
                    </div>

I get a lot of errors on the console as follows,

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: 

I dont have any watch on my collection. What is the correct way to do this.

Upvotes: 2

Views: 572

Answers (1)

Josep
Josep

Reputation: 13071

I would advise you against using that implementation of the 'groupBy' $filter, use this one instead:

angular.module("sbrpr.filters", [])
.filter('groupBy', function () {
  var results={};
    return function (data, key) {
        if (!(data && key)) return;
        var result;
        if(!this.$id){
            result={};
        }else{
            var scopeId = this.$id;
            if(!results[scopeId]){
                results[scopeId]={};
                this.$on("$destroy", function() {
                    delete results[scopeId];
                });
            }
            result = results[scopeId];
        }

        for(var groupKey in result)
          result[groupKey].splice(0,result[groupKey].length);

        for (var i=0; i<data.length; i++) {
            if (!result[data[i][key]])
                result[data[i][key]]=[];
            result[data[i][key]].push(data[i]);
        }

        var keys = Object.keys(result);
        for(var k=0; k<keys.length; k++){
          if(result[keys[k]].length===0)
            delete result[keys[k]];
        }
        return result;
    };
});

Also, have a look at this post, where I discuss why the implementation that you are using is actually pretty bad.

And finally, please support my answer here. Thanks!

Upvotes: 2

Related Questions