Alex Soroka
Alex Soroka

Reputation: 810

Array filter cause infinite $digest loop

I have two collections of objects. One of them have objects with primitive values, another one with objects values.

I need to render collection in html table with dynamic columns. I have made a filter for this, but it's work for collection with primitive object value and cause infinite $digest loop(see console) for collection with objects.

Here is a JSBin

I understand that problem is in returning a new object each time due to angular.copy. But why does it work for primitive value?

Any ideas how I can solve this problem?

Upvotes: 0

Views: 473

Answers (2)

Alex Soroka
Alex Soroka

Reputation: 810

I solved my question but because there are many similar questions without answers in SO I decided to post my answer.

The key to solving the problem is fact that ng-repeat don't use neither $watch nor $watch with Equality. It uses $watchCollection to watch collection =). In my case when filter returns new copied object with primitive values $watchCollection doesn't fire(standard $watch do in this case) so I avoid infinite $digest loop. But in case object with object value $watchCollection triggers infinite $digest loop($watch with Equality=true doesn't).

Here is jsbin

Upvotes: 0

Tahsis Claus
Tahsis Claus

Reputation: 1929

The reason it works for primitives is JS passes primitives by value, rather than by reference. The problem can be solved with lodash's (the _ library) memoize function. This page details the exact problem and solution using memoize.

Upvotes: 1

Related Questions