Recursive custom directives using ngRepeat

家住魔仙堡 提交于 2019-12-04 02:07:24
Ye Liu

The problem is that you're trying to define your directive recursively, when angular was trying to compile the template, it saw treeview directive, it called treeview's compile function, then it saw treeviewItem directive, it called treeviewItem's compile function, then it saw treeviewItem directive, it called treeviewItem's compile function,then it saw treeviewItem directive, it called treeviewItem's compile function...

See the problem? The calls to compile functions couldn't stop. So, you need to pull the recursive definition out of your template, but use $compile to build DOM manually:

module.directive('treeviewItem', function ($compile) {
    return {
        restrict: 'E',
        template: '<li><i class="icon-plus-sign"></i><a href="/"><i class="icon-folder-close"></i>{{item.text}}</a></li>',
        replace: true,
        scope: {
            item: "="
        },
        link: function (scope, element, attrs) {
            element.append($compile('<ul><treeview-item ng-repeat="childitem in item.childitems" item="childitem"></treeview-item></ul>')(scope));

            console.log("treeview item directive loaded");
        }
    };
});

http://jsfiddle.net/SKPpv/3/

Alternatively, I found a solution to display tree-like data on SO https://stackoverflow.com/a/11861030/69172. The solution however uses ngInclude instead of directives.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!