anson
anson

Reputation: 4164

Use of "for...of" in ng-repeat

Looking through ng-repeats source, it doesn't look like theres any instance of it using for-of. Is there any custom directive that does this or some other way of achieving this loop in templates to make use of iterator functions?

Class with iterator

class Cache{

  constructor(items){
    this.cache = {
      "one" : 1,
      "two" : 2
    };
  };

  // custom iterator that turns our cache into an array
  // for use in "for...of" loops
  [Symbol.iterator](){
    var index = 0;
    // turn cache object into array of its values (underscore method)
    var data = _.values(this.cache);

    return {
      next: function(){
        if(index < data.length){
          return {
            value: data[index++],
            done: false
          };
        }else{
          return { done:true };
        }
      }
    };
  };

};

var myCache = new Cache();
// looping my cache in simple js would look like
for(let val of myCache){
  console.log(val);
}
// 1, 2

proposed angularjs ng-repeat directive

<ul>
  <li ng-repeat="item in myCache track by $index"></li>
</ul>

However that does not work as ng-repeat does not implement for...of. My question is: is there a way to get the ng-repeat directive to work nicely with iterators with minimal interface changes, or better yet, a custom directive identical to ng-repeat that is made for for...of loops?

Upvotes: 4

Views: 1064

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

You could just use Array.from to convert your iterable source to an array, which ngRepeat will be able to iterate:

<ul>
  <li ng-repeat="item in Array.from(myCache) track by $index"></li>
</ul>

Ideally this would happen in your javascript directive/controller:

scope.myCache = Array.from(new Cache());

View:

<ul>
  <li ng-repeat="item in myCache track by $index"></li>
</ul>

Upvotes: 1

Related Questions