使用" for ... of"在ng-repeat中

时间:2016-05-08 19:36:16

标签: javascript angularjs angularjs-ng-repeat ecmascript-6

通过ng-repeats源查看,使用for-of看起来并不像它的任何实例。是否有任何自定义指令执行此操作或在模板中实现此循环的其他方式来使用迭代器函数?

带迭代器的类

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

提出了angularjs ng-repeat指令

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

然而,这不起作用,因为ng-repeat没有实现for...of。我的问题是:有没有办法让ng-repeat指令与带有最小接口更改的迭代器很好地协同工作,或者更好的是,一个与为{{{ 1}}循环?

1 个答案:

答案 0 :(得分:1)

您可以使用Array.from将可迭代的源代码转换为.pdf将能够迭代的数组:

ngRepeat

理想情况下,这会发生在你的javascript指令/控制器中:

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

查看:

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