November 24, 2013

Avoiding Angular's Digest Cycles Limit Reached

Hi guys,
I've recently encountered an issue where in a certain view on an Angular application I've reached the digest cycle limit. If you got here, 80% that you've reached the same issue yourselves.
I would like to elaborate here on how I've managed to avoid it, and fix the issue. It might not work for all the variation of this problem, but it is worth trying before you go into more serious measures.

Avoid calling processing-function from the view
I’m talking about manipulating data from the view in order for it to suite the view needs, e.g. ng-repeat=”value in yourFunction(scopeMemeber)”
If you need to manipulate the data for your view, do it on the logic tier, which is the controller.
Try to use only $scope member directly on the view.

When preparing data on the controller, avoid referencing $scope members up until the very end
If you’re getting a value from some service and on the controller you’re start to “work” on it, try to avoid referencing $scope members in it, since any change to them is a potential dirty-check loop.
What you want to do is try and save the assignment to the $scope member to the very end. Manipulate you’re data using plain JS, and only in the end make the assignment to the $scope member.
Note that sometimes it would even be more efficient to copy an Object, just to make sure it is not linked to the $scope anymore…

Put Sorting, Filtering, etc. outside of the view if possible
Although Angular offers nice ways to sort, order, filtering, etc. as a part of their API on the view level, I would be much better to do that on the logic tier (controller) when the view is complex and have a lot of these.
It is sometimes more efficient to order and array and assign it to the $scope member again, than to do it on the view.

If you have more suggestion, I would be happy to hear about it :)


No comments: