how to write a 'double' and a 'ntimes' directive for angularjs?

前端 未结 2 1152
有刺的猬
有刺的猬 2021-01-31 00:22

I am having trouble understand the \'ngRepeat\' directive so I wish to learn how angularjs works by writing a \'double\' directive and then extending with an \'ntimes\' directiv

2条回答
  •  北海茫月
    2021-01-31 01:08

    
     

    Hello World - 2

    Hello World - 10

    More text

    The directives below will remove the , , and tags:

    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

    I used a compile function rather than a linking function because it seemed like only template DOM manipulation was required.

    Update: I like this implementation of the ntimes compile function better:

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

提交回复
热议问题