javascript - 如何为 angularjs 编写 'double' 和 'ntimes' 指令?

标签 javascript angularjs

我无法理解“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> 

最佳答案

<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());
        }
    }
});​

Fiddle

我使用编译函数而不是链接函数,因为它似乎只需要模板 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);
}

关于javascript - 如何为 angularjs 编写 'double' 和 'ntimes' 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13852248/

相关文章:

javascript - xhtml 中指定命名空间的自定义标签

javascript - 如何使用 angular.js 推送通知?

javascript - 将 NodeJS express 对象传递给 AngularJS 1.6

javascript - Angular JS $http Promise 的行为是否像真正的 $q Promise 一样?

javascript - 带重复的背包 - 阵列解决方案

javascript - Ajax JSON异常意外的 token [

javascript - 道场/dom准备好了!和道场/准备澄清

javascript - Route中的渲染组件不会触发其componentDidMount

javascript - 将数组绑定(bind)到 AngularJS 中的对象属性时忽略虚假值

Angularjs - 下拉多选