javascript - 了解 AngularJS $compile 函数

标签 javascript html angularjs

我尝试使用 AngularJS 构建包含 n 个子菜单的菜单。 这是我的范围:

$scope.menu = [
                    {"type": "folder", "name": "TestFolder1", "subfolder": []},
                    {"type": "folder", "name": "TestFolder2", "subfolder": [
                        {"type": "folder", "name": "TestFolder2", "subfolder": [
                            {"type": "folder", "name": "TestFolder2", "subfolder": []},
                            {"type": "folder", "name": "TestFolder2", "subfolder": []}
                        ]},
                        {"type": "folder", "name": "TestFolder2", "subfolder": []}
                    ]},
                    {"type": "file", "name": "testfile"}
            ];

这是我的指令

codeApp.directive('item', ['$compile', function ($compile) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                item: '='
            },
            template: '<li>'+
            '<a id="item"><i class="fa fa-code-fork fa-fw"></i>{{item.name}}</a>'+
            '</li>',
            link: function($scope, $element) {
                if (angular.isArray($scope.item.subfolder) && $scope.item.subfolder.length > 0) {
                    $element.append('<ul><item ng-repeat="childItem in item.subfolder" item="childItem"></item></ul>');
                    $compile($element.contents())($scope);
                }
            }
        };
    }]);

我的第一行是这样的:

<item ng-repeat="item in menu" item="item"></item>

菜单已创建,但仅第一级且 我不确定编译功能是如何工作的。如何才能将该行附加到 后面?

最佳答案

我认为这里已经讨论了类似的问题: https://stackoverflow.com/a/18609594/4360457

答案包括一个 plunkr 示例,并且解释得很好。

关于javascript - 了解 AngularJS $compile 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28110666/

相关文章:

javascript - CORS 服务器端与客户端?为什么一个有效,而另一个却无效?

javascript - 只有 office 版本更改问题

html - 如何对齐输入表单?

angularjs - 将 Debounce/Throttle 添加到 AngularJS ng-repeat 过滤器

javascript - PHP中的执行函数取决于Angular发送的whatsapp

javascript - 了解 backbone.js 属性和 toJSON()

javascript - 无法使用 javascript 抓取和操作 HTML 元素

javascript - 如何根据 child 在 DOM 树中的位置选择 child

javascript - 类型错误 : getElementById is null using JSP

javascript - 错误 : <svg> attribute height: Expected length, "NaN"