Angular JS ng-repeat - dynamic collection track

I am trying to do ng-repeat

on the result of a function call like

<body ng-init='a = [1, 2, 3]'>
  <div ng-repeat='item in f(a) track by item[0]'>{{item}}</div>
</body>

      

where f

is

function f (arr) {
    return arr.map(function (v) {
      return [v]
    })
  }

      

Here is a Plunker with this code

The problem is that in the console we can see errors like 10 $digest() iterations reached. Aborting!

This is not due to recreating the container array, because if we just change line 3

how

return [v] -> return v

      

and remove

track by item[0] 

      

everything is working. This is due to the re-creation of the elements, and track by

must deal with it. But for some reason this is not the case :(

I also tried to solve the problem without track by

buying a constant $$hashKey

for each item (even the collection itself). Here's a Plunker with the same error. Hope someone can explain why this doesn't work.

So there are two separate questions: case with track by

and case with$$hashKey

By the way, I am reading How to iterate over the elements returned by a function using ng-repeat? and AngularJS InfDig error (infinite loop) with ng-repeat function that returns an array of objects more than a few times, but cannot find an answer there

thank

+3


source to share


2 answers


Is there a reason why you cannot compute the result and then display it? That is, have ng-init="a = [0,1,2]; fa = f(a);"

, and then ng-repeat="item in fa"

?

Working plunkr example



If you need this computed result to update on changes a

, you could simply have an operator $scope.$watch

watching for changes in a

and then update fa

.

+1


source


Ok, here is a hack we could use to solve a case without track by

or$$hashKey

ng-repeat="item in t = angular.equals(t, f(a)) ? t : f(a)"

      



But it does answer the question of why the examples in question don't work. So please if you know the answer - post it - I would really appreciate

0


source







All Articles