sisimh
sisimh

Reputation: 1337

custom filters 10 $digest iterations reached?

I have 10 select list with more than 10 options per each , and I have this error due to the maximum number of digest loop that angular set to 10 ,

on these select lists I apply these two custom filters and causing the error :

10 $digest() iterations reached. Aborting

app.filter('sortFilter', function() {
    return function(items) {
        items.sort(function (item1, item2) {
          return (item1.order > item2.order ? 1 : -1);
        });
        return items;
    };
});


app.filter('removeDuplicationFilter', function() {
    return function(items, thisOption) {
        var options=[];
        angular.forEach(items, function(item) {
             if ( item.order == 0 ) {
                options.push(item);
            } else if (thisOption == item.name) {
                options.push(item);
            }
        });
        return options;
    };
});

<div ng-repeat="field in fields|sortFilter" ng-if="filterField.order">
 <select ng-model="field.name" ng-options="item.name as item.label for item in fields | removeDuplicationFilter:field.name"></select>
</div>

Please advice , Thanks

UPDATE: JS FIDDLE

Upvotes: 1

Views: 1072

Answers (1)

lex82
lex82

Reputation: 11317

The problem is that your sortFilter modifies the value its supposed to filter, i.e., it changes the model. This in turn triggers another digest cycle and sorting happens again. You can easily fix it by returning a sorted copy of the array like this:

myApp.filter('sortFilter', function() {
    return function(items) {
        var result = items.concat([]); // copies the array
        result.sort(function (item1, item2) {
          return (item1.order > item2.order ? 1 : -1);
        });
        return result;
    }
});

Upvotes: 1

Related Questions