简体   繁体   中英

Recursion in angular directives / templates

I was trying to build a custom directive for displaying a tree. For some reason it seems that once you include the directive in its own template, something runs wild in the angular compiler and the browser process gets stuck in a loop. Here's a plunker:

<li class="list-group-item">
<a ng-click="clicked(item)"><span ng-if="item.items" class="glyphicon glyphicon-plus text-primary"></span></a>
<span ng-if="!item.items" class="glyphicon glyphicon-record text-primary"></span>
<a>{{item.name}}</a>
<div ng-if="item.items && item.items.length>0">
    <ul class="list-group"> 
        <taxonomy-item ng-if="item.items && item.items.length>0" ng-repeat="child in item.items"></taxonomy-item>
    </ul>
</div>

If you pay attention you'll see that it doesn't even bind data, so it shouldn't be a recursive loop caused by model/data, but rather a compiler issue...

http://plnkr.co/edit/1aollcuCr2gA96W6Sk6q

Careful, running might freeze your browser tab!

Any suggestions on how to work around this problem?

The solution is quite simple. Since angular doesn't permit the usage of directives within themselves, you need to make use of the link function, to add the child directive afterwards. A minimal example:

myApp.directive("myDirective", ["$compile",function($compile){

    var template = '<my-directive ng-repeat="child in item.items" ng-model="child"></my-directive>';

    return{
        templateUrl: "myDirective.html",
        replace: true,
        transclude: true,
        scope: {
            item: "=ngModel"    
        },
        link: function(scope, element){                     
            var compiled = $compile(template)(scope);
            element.append(compiled);
        }
    }   
}]);

This won't cause any trouble, since the compiled child directive is self-contained and compiled afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM