2016-05-08 5 views
3

ng-repeatsソースから見ると、for-ofを使用しているインスタンスのようには見えません。イテレータ関数を利用するために、このループをテンプレートで実現するカスタムディレクティブはありますか?イテレータng-repeatで "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 

クラスはNG-repeatがfor...ofを実装していないと動作しないことが

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

angularjs NGリピートディレクティブを提案しました。私の質問です:最小のインターフェイスの変更、またはより良いまだ、ループのfor...ofのために作られたng-repeatと同じより良い、イテレータでng-repeatディレクティブをうまく動作させる方法がありますか?

+0

これはあなたを助けることがあります。 http://stackoverflow.com/questions/11873570/angularjs-for-loop-with-numbers-ranges –

+1

ng-repeatの構文は 'object in array'または'(key、value)in object'です。あなたは何を達成しようとしていますか? –

+0

が例として更新されました – anson

答えて

1
あなただけ繰り返すことができるようになります ngRepeat配列のために、反復可能なソースを変換する Array.fromを使用することができ

<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> 
+0

ありがとう、このようなもの、または同様のものは、私がカスタムリピート指令を書かずに探しているものに最も近いものかもしれません。私は本当に弱いインターフェースを望んでいましたが、ng-repeatは単純にそれを実装していないことを理解しています。 – anson

関連する問題