【问题标题】:how to write a 'double' and a 'ntimes' directive for angularjs?如何为 angularjs 编写“double”和“ntimes”指令?
【发布时间】:2012-12-13 03:00:48
【问题描述】:

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

'双'

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

会产生:

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

'ntimes'

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

会产生:

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

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:
    <double>
     <h1>Hello World - 2</h1>
    </double>
    
    <ntimes repeat=10>
        <h1>Hello World - 10</h1>
        <h4>More text</h4>
    </ntimes>
    

    以下指令将删除&lt;double&gt;, &lt;/double&gt;, &lt;ntimes ...&gt;&lt;/ntimes&gt; 标签:

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

    【讨论】:

    • 在原始样本中,为什么最后会有tElement.replaceWith? tElement 在 replaceWith 之前不是已经一样了吗?
    • @mr_eko tElement.replaceWith 用它的子元素替换元素。所以&lt;double&gt;&lt;h1&gt;Hello World - 2&lt;/h1&gt;&lt;/double&gt; 会变成&lt;h1&gt;Hello World - 2&lt;/h1&gt;&lt;h1&gt;Hello World - 2&lt;/h1&gt; 被替换)。
    • 非常好的例子作为编译函数的使用
    • 为什么不使用克隆指令就不能工作?当我注销 content.clone 和 content 时,它们似乎是同一回事
    • @Mark Rajcok 我稍微修改了您的示例,在double 指令的内容中添加了一些属性指令。这是链接jsfiddle.net/wjkv83ta 并得到了奇怪的行为:第一个元素没有正确解析。你可以看到它,因为只有第二个元素变红了。
    【解决方案2】:

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

    如果您真的只想克隆元素,请尝试以下操作:http://jsfiddle.net/hp9d7/

    【讨论】:

    • 谢谢!我刚刚意识到您使用链接阶段来添加元素。是否也可以使用绑定来做到这一点?
    猜你喜欢
    • 2013-01-15
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2015-02-16
    • 1970-01-01
    • 2014-04-02
    • 2013-06-09
    相关资源
    最近更新 更多