Recursion in Angular directives

前端 未结 9 1505
不思量自难忘°
不思量自难忘° 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:51

    Manually adding elements and compiling them is definitely a perfect approach. If you use ng-repeat then you will not have to manually remove elements.

    Demo: http://jsfiddle.net/KNM4q/113/

    .directive('tree', function ($compile) {
    return {
        restrict: 'E',
        terminal: true,
        scope: { val: '=', parentData:'=' },
        link: function (scope, element, attrs) {
            var template = '{{val.text}}';
            template += '';
    
            if (angular.isArray(scope.val.items)) {
                template += '
    '; } scope.deleteMe = function(index) { if(scope.parentData) { var itemIndex = scope.parentData.indexOf(scope.val); scope.parentData.splice(itemIndex,1); } scope.val = {}; }; var newElement = angular.element(template); $compile(newElement)(scope); element.replaceWith(newElement); } } });

提交回复
热议问题