如何为angularjs写一个'double'和'ntimes'指令?

zca*_*ate 14 javascript angularjs

我无法理解'ngRepeat'指令,因此我希望通过编写'double'指令然后使用'ntimes'指令进行扩展来了解angularjs的工作原理:so

'双'

<double>
 <h1>Hello World</h1>
</double>
Run Code Online (Sandbox Code Playgroud)

会导致产生:

 <h1>Hello World</h1>
 <h1>Hello World</h1>
Run Code Online (Sandbox Code Playgroud)

"N次"

<ntimes repeat=10>
 <h1>Hello World</h1>
</ntimes>
Run Code Online (Sandbox Code Playgroud)

会导致产生:

 <h1>Hello World</h1> 
 .... 8 more times....
 <h1>Hello World</h1> 
Run Code Online (Sandbox Code Playgroud)

Mar*_*cok 29

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

<ntimes repeat=10>
    <h1>Hello World - 10</h1>
    <h4>More text</h4>
</ntimes>
Run Code Online (Sandbox Code Playgroud)

下面的指令将删除<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());
        }
    }
});?
Run Code Online (Sandbox Code Playgroud)

小提琴

我使用了编译函数而不是链接函数,因为它似乎只需要模板DOM操作.

更新:我更喜欢ntimes编译函数的这个实现:

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);
}
Run Code Online (Sandbox Code Playgroud)


bml*_*ite 6

ng-repeat指令主要用于迭代列表/数组/集合(即ng-repeat="item in list")上的项目,并且不仅仅是克隆元素.请查看angularjs ng-repeat指令文档.

如果你真的只想克隆元素,试试这样的东西:http://jsfiddle.net/hp9d7/