Recursion in Angular directives

前端 未结 9 1499
不思量自难忘°
不思量自难忘° 2020-11-22 04:24

There are a couple of popular recursive angular directive Q&A\'s out there, which all come down to one of the following solutions:

  • manually incrementally \
9条回答
  •  有刺的猬
    2020-11-22 04:50

    I don't know for sure if this solution is found in one of the examples you linked or the same basic concept, but I had a need of a recursive directive, and I found a great, easy solution.

    module.directive("recursive", function($compile) {
        return {
            restrict: "EACM",
            priority: 100000,
            compile: function(tElement, tAttr) {
                var contents = tElement.contents().remove();
                var compiledContents;
                return function(scope, iElement, iAttr) {
                    if(!compiledContents) {
                        compiledContents = $compile(contents);
                    }
                    iElement.append(
                        compiledContents(scope, 
                                         function(clone) {
                                             return clone; }));
                };
            }
        };
    });
    
    module.directive("tree", function() {
        return {
            scope: {tree: '='},
            template: '

    {{ tree.text }}

    ', compile: function() { return function() { } } }; });​

    You should create the recursive directive and then wrap it around the element that makes the recursive call.

提交回复
热议问题