39

I receive data from my back end server structured like this:

{
  name : "Mc Feast",
  owner :  "Mc Donalds"
}, 
{
  name : "Royale with cheese",
  owner :  "Mc Donalds"
}, 
{
  name : "Whopper",
  owner :  "Burger King"
}

For my view I would like to "invert" the list. I.e. I want to list each owner, and for that owner list all hamburgers. I can achieve this by using the underscorejs function groupBy in a filter which I then use in with the ng-repeat directive:

JS:

app.filter("ownerGrouping", function() {
  return function(collection) {
    return _.groupBy(collection, function(item) {
      return item.owner;
    });
  }
 });

HTML:

<li ng-repeat="(owner, hamburgerList) in hamburgers | ownerGrouping">
  {{owner}}:  
  <ul>
    <li ng-repeat="burger in hamburgerList | orderBy : 'name'">{{burger.name}}</li>
  </ul>
</li>

This works as expected but I get an enormous error stack trace when the list is rendered with the error message "10 $digest iterations reached". I have a hard time seeing how my code creates an infinite loop which is implied by this message. Does any one know why?

Here is a link to a plunk with the code: http://plnkr.co/edit/8kbVuWhOMlMojp0E5Qbs?p=preview

7 Answers 7

58

This happens because _.groupBy returns a collection of new objects every time it runs. Angular's ngRepeat doesn't realize that those objects are equal because ngRepeat tracks them by identity. New object leads to new identity. This makes Angular think that something has changed since the last check, which means that Angular should run another check (aka digest). The next digest ends up getting yet another new set of objects, and so another digest is triggered. The repeats until Angular gives up.

One easy way to get rid of the error is to make sure your filter returns the same collection of objects every time (unless of course it has changed). You can do this very easily with underscore by using _.memoize. Just wrap the filter function in memoize:

app.filter("ownerGrouping", function() {
  return _.memoize(function(collection, field) {
    return _.groupBy(collection, function(item) {
      return item.owner;
    });
  }, function resolver(collection, field) {
    return collection.length + field;
  })
});

A resolver function is required if you plan to use different field values for your filters. In the example above, the length of the array is used. A better be to reduce the collection to a unique md5 hash string.

See plunker fork here. Memoize will remember the result of a specific input and return the same object if the input is the same as before. If the values change frequently though then you should check if _.memoize discards old results to avoid a memory leak over time.

Investigating a bit further I see that ngRepeat supports an extended syntax ... track by EXPRESSION, which might be helpful somehow by allowing you to tell Angular to look at the owner of the restaurants instead of the identity of the objects. This would be an alternative to the memoization trick above, though I couldn't manage to test it in the plunker (possibly old version of Angular from before track by was implemented?).

5
  • I looked into the track by solution, and I agree it sure looks like it should work. However, I got plunkr working with a version of angular which supports track by, and I did "track by owner", but I'm still getting the same 10 digests error. Not sure why it doesn't solve the problem: plnkr.co/edit/0oE6MGjXum7ZYCWGEJxk?p=preview
    – Jonah
    Commented May 13, 2013 at 1:52
  • track by uses the property you specify as the unique identifier of the object. it simply keeps Angular from creating item.$id. This feature is only useful if the data in the property is unique per object, which is not the case in the given sample data (there is more than one owner "Mc Donalds"). The memoize solution seems to be the way to go in your situation, since, as was stated, _.groupBy by nature returns a new (and therefore different) object, even given identical input. Commented Jul 26, 2013 at 20:21
  • 1
    This memoize idea here is great, but I'm curious if there's another way around it? In my instance, I don't want to memoize the particular objects because they hold properties of state that may or may not be relevant at their memoize recall point.
    – Clev3r
    Commented Jun 10, 2014 at 20:59
  • 2
    To avoid memory leak, i clear the result cache a soon as $digest is done using setTimeout(function(){ memoizedFunc.cache = {} }) Don't use $timeout, because it will trigger $digest again
    – cnlevy
    Commented Sep 14, 2014 at 17:34
  • Of course that you can use $timeout, just set 3rd parameter to false. $timeout(fn, delay, false); Commented Dec 18, 2014 at 21:49
13

Okay, I think I figured it out. Start by taking a look at the source code for ngRepeat. Notice line 199: This is where we set up watches on the array/object we are repeating over, so that if it or its elements change a digest cycle will be triggered:

$scope.$watchCollection(rhs, function ngRepeatAction(collection){

Now we need to find the definition of $watchCollection, which begins on line 360 of rootScope.js. This function is passed in our array or object expression, which in our case is hamburgers | ownerGrouping. On line 365 that string expression is turned into a function using the $parse service, a function which will be invoked later, and every time this watcher runs:

var objGetter = $parse(obj);

That new function, which will evaluate our filter and get the resulting array, is invoked just a few lines down:

newValue = objGetter(self);

So newValue holds the result of our filtered data, after groupBy has been applied.

Next scroll down to line 408 and take a look at this code:

        // copy the items to oldValue and look for changes.
        for (var i = 0; i < newLength; i++) {
          if (oldValue[i] !== newValue[i]) {
            changeDetected++;
            oldValue[i] = newValue[i];
          }
        }

The first time running, oldValue is just an empty array (set up above as "internalArray"), so a change will be detected. However, each of its elements will be set to the corresponding element of newValue, so that we expect the next time it runs everything should match and no change will be detected. So when everything is working normally this code will be run twice. Once for the setup, which detects a change from the initial null state, and then once again, because the detected change forces a new digest cycle to run. In the normal case no changes will be detected during this 2nd run, because at that point (oldValue[i] !== newValue[i]) will be false for all i. This is why you were seeing 2 console.log outputs in your working example.

But in your failing case, your filter code is generating a new array with new elments every time it's run. While this new array's elments have the same value as the old array's elements (it's a perfect copy), they are not the same actual elements. That is, they refer to different objects in memory that simply happen to have the same properties and values. Hence in your case oldValue[i] !== newValue[i] will always be true, for the same reason that, eg, {x: 1} !== {x: 1} is always true. And a change will always be detected.

So the essential problem is that your filter is creating a new copy of the array every time it's run, consisting of new elements that are copies of the original array's elments. So the watcher setup by ngRepeat just gets stuck in what is essentially an infinite recursive loop, always detecting a change and triggering a new digest cycle.

Here's a simpler version of your code that recreates the same problem: http://plnkr.co/edit/KiU4v4V0iXmdOKesgy7t?p=preview

The problem vanishes if the filter stops creating a new array every time it's run.

3
  • You are on to something, but it's not really about the array being created every time. ngRepeat doesn't care about the identity of the array, but rather about the elements inside the array. Se this fork which still returns a new array every time, but caches the internal element: No errors :) Meanwhile, this fork makes sure to return the same array every time, but creates a new internal element every time: Error.
    – Supr
    Commented May 12, 2013 at 23:31
  • @Supr, Thanks for the very nice catch. I re-read the source code and found my misunderstanding, and corrected the post to reflect your insight.
    – Jonah
    Commented May 13, 2013 at 1:04
  • 1
    @Supr and Jonah. Thank you both for what seems to be hard detective work that gave me very valuable insight to how angular works. Commented May 13, 2013 at 8:54
4

New to AngularJS 1.2 is a "track-by" option for the ng-repeat directive. You can use it to help Angular recognize that different object instances should really be considered the same object.

ng-repeat="student in students track by student.id"

This will help unconfuse Angular in cases like yours where you're using Underscore to do heavyweight slicing and dicing, producing new objects instead of merely filtering them.

0
2

Thanks for the memoize solution, it works fine.

However, _.memoize uses the first passed parameter as the default key for its cache. This could not be handy, especially if the first parameter will always be the same reference. Hopefully, this behavior is configurable via the resolver parameter.

In the example below, the first parameter will always be the same array, and the second one a string representing on which field it should be grouped by:

return _.memoize(function(collection, field) {
    return _.groupBy(collection, field);
}, function resolver(collection, field) {
    return collection.length + field;
});
1
  • Yes, thanks for this, you need this resolver callback if you want to use different arguments for your filter.
    – ilovett
    Commented Jul 14, 2015 at 20:28
2

Pardon the brevity, but try ng-init="thing = (array | fn:arg)" and use thing in your ng-repeat. Works for me but this is a broad issue.

2
  • 1
    Only thing that worked for me, even though I've used track by in other circumstances. Thanks! Commented Oct 16, 2015 at 0:05
  • You saved my days Commented Sep 3, 2016 at 22:18
0

I am not sure why this error is coming but, logically the filter function gets called for each element for the array.

In your case the filter function that you have created returns a function which should only be called when the array is updated, not for each element of the array. The result returned by the function can then be bounded to html.

I have forked the plunker and have created my own implementation of it here http://plnkr.co/edit/KTlTfFyVUhWVCtX6igsn

It does not use any filter. The basic idea is to call the groupBy at the start and whenever an element is added

$scope.ownerHamburgers=_.groupBy(hamburgers, function(item) {
      return item.owner;
    });



$scope.addBurger = function() {
    hamburgers.push({
      name : "Mc Fish",
      owner :"Mc Donalds"
    });
    $scope.ownerHamburgers=_.groupBy(hamburgers, function(item) {
      return item.owner;
    });
  }
5
  • I did not know that a filter was called more than once, but i did some testing with simpler structures and the filter does not get called once for each element in the list. Did you mean that this is always the case or only in my example? In this simpler plunk you can see that the filter is called twice when the filter is first used, and twice each time the list is modified. I also find this strange plnkr.co/edit/EtOVSit77O4wc3zkhFCA?p=preview Commented May 12, 2013 at 15:24
  • @LudwigMagnusson, the error is definitely being caused by the filter getting called more than 10 times. Take a look at line 5 of app.js in this fork of your plunker: plnkr.co/edit/Jvhk0K6LA3cQmrGREwsP?p=preview. Then look at the console output and you'll see "called" 11 times and then the error. I think the easiest solution is simply to get your groupBy structure setup before you enter the repeat.
    – Jonah
    Commented May 12, 2013 at 16:08
  • @Jonah I understand that it is true in this case. I just wanted to point out that this is not always the case and I wanted to understand why it was so here. I am considering the solution propsed... =) Commented May 12, 2013 at 16:12
  • @LudwigMagnusson, ah, sorry i misunderstood. can you link to one of your examples when it is not the case, and i'll look into it. i'd like to know as well.
    – Jonah
    Commented May 12, 2013 at 16:42
  • @Jonah From my first comment. plnkr.co/edit/EtOVSit77O4wc3zkhFCA?p=preview The filter method is run twice and not once per object in the array. Commented May 12, 2013 at 16:44
0

For what it's worth, to add one more example and solution, I had a simple filter like this:

.filter('paragraphs', function () {
    return function (text) {
        return text.split(/\n\n/g);
    }
})

with:

<p ng-repeat="p in (description | paragraphs)">{{ p }}</p>

which caused the described infinite recursion in $digest. Was easily fixed with:

<p ng-repeat="(i, p) in (description | paragraphs) track by i">{{ p }}</p>

This is also necessary since ngRepeat paradoxically doesn't like repeaters, i.e. "foo\n\nfoo" would cause an error because of two identical paragraphs. This solution may not be appropriate if the contents of the paragraphs are actually changing and it's important that they keep getting digested, but in my case this isn't an issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.