14

「ngRepeat」ディレクティブを理解するのに苦労しているので、「double」ディレクティブを作成してから「ntimes」ディレクティブで拡張することにより、angularjs がどのように機能するかを学びたいと考えています。

'ダブル'

<double>
 <h1>Hello World</h1>
</double>

結果として次のものが生成されます。

 <h1>Hello World</h1>
 <h1>Hello World</h1>

「n回」

<ntimes repeat=10>
 <h1>Hello World</h1>
</ntimes>

結果として次のものが生成されます。

 <h1>Hello World</h1> 
 .... 8 more times....
 <h1>Hello World</h1> 
4

2 に答える 2

29
<double>
 <h1>Hello World - 2</h1>
</double>

<ntimes repeat=10>
    <h1>Hello World - 10</h1>
    <h4>More text</h4>
</ntimes>

以下のディレクティブは、 タグ<double>, </double>, <ntimes ...></ntimes>タグを削除します。

var app = angular.module('app', []);
app.directive('double', function() {
    return {
        restrict: 'E',
        compile: function(tElement, attrs) {
            var content = tElement.children();
            tElement.append(content.clone());
            tElement.replaceWith(tElement.children());
        }
    }
});
app.directive('ntimes', function() {
    return {
        restrict: 'E',
        compile: function(tElement, attrs) {
            var content = tElement.children();
            for (var i = 0; i < attrs.repeat - 1; i++) {
                tElement.append(content.clone());
            }
            tElement.replaceWith(tElement.children());
        }
    }
});​

フィドル

テンプレート DOM 操作のみが必要と思われるため、リンク関数ではなくコンパイル関数を使用しました。

更新: ntimes compile 関数のこの実装の方が気に入っています。

compile: function(tElement, attrs) {
    var content = tElement.children();
    var repeatedContent = content.clone();
    for (var i = 2; i <= attrs.repeat; i++) {
        repeatedContent.append(content.clone());
    }
    tElement.replaceWith(repeatedContent);
}
于 2012-12-14T05:18:58.823 に答える
6

このng-repeatディレクティブは、主にリスト/配列/コレクション (つまりng-repeat="item in list") の項目を反復処理するために使用され、単純に要素を複製する以上のことを行います。angularjs ng-repeat ディレクティブ ドキュメントをご覧ください。

本当に要素を複製したいだけなら、次のようにしてみてください: http://jsfiddle.net/hp9d7/

于 2012-12-13T15:24:37.647 に答える