【问题标题】:Use of "for...of" in ng-repeat在 ng-repeat 中使用“for...of”
【发布时间】:2016-09-03 09:29:41
【问题描述】:

查看 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 指令与具有最小接口更改的迭代器很好地配合使用,或者更好的是,一个与 ng-repeat 相同的自定义指令,它是为 @987654327 制作的@循环?

【问题讨论】:

  • 这可能对你有帮助:stackoverflow.com/questions/11873570/…
  • ng-repeat 的语法是object in array(key, value) in object。你想达到什么目标?
  • 用示例更新
  • 必须同意MuliYulzary,如果你只是想迭代一个对象,你不需要创建自定义迭代器,因为a)ngRepeat已经可以迭代对象,b)ES2016特性@ 987654323@ 已经提供了这个实现
  • 这不是为了改变我的实现。我知道(当然)还有很多其他方法可以构建我的代码,这些方法可以与 ng-repeat 一起使用。我的问题更多的是“如果我想使用带有角度模板的迭代器函数,可以吗?是否有允许这样做的自定义指令(ng-repeat 除外)?”

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


【解决方案1】:

您可以使用Array.from 将您的可迭代源转换为一个数组,ngRepeat 将能够对其进行迭代:

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

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

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

查看:

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

【讨论】:

  • 谢谢,这样或类似的东西可能是最接近我正在寻找的东西,而无需编写自定义重复指令。我真的希望有一个不那么侵入性的界面,但我知道 ng-repeat 根本没有实现它。
猜你喜欢
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多