是否有可能引用其自身内部角定制指令? [英] Is it possible to reference Angular custom directive inside itself?

查看:119
本文介绍了是否有可能引用其自身内部角定制指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

展望落实角文件夹层次:

Looking to implement folder hierarchy in Angular:

我通过本身引用它的模板内自定义指令实现这一点。

I'm implementing this via custom directive that references itself inside its template.

目前它进入无限循环使用此设置:

Currently it's going into infinite loop with this setup:

<!-- index.html -->
<subfolders folder="default_folder"></subfolders>

这是&LT;&子GT; 指令:

//subfoldersDirective.js
angular.module('app').directive('subfolders', subfolders);
function subfolders() {

    var directive = {
        restrict: 'AE',
        scope: {
            folder: '=',
        },
        templateUrl: '/pathto/subfoldersDirective.html',
        controller: DirCtrl,
        controllerAs: 'vm'
    };

    return directive;

    function DirCtrl($scope) {
        var vm = this;
        vm.folder = $scope.folder;
    }

}

和它的模板:

<!-- folderDirective.html -->
<div ng-repeat="folder in vm.folder.subfolders">
    {{ folder.name }}
    <button ng-click="folder.is_open = true">Open folder</button>
    <div ng-if="folder.is_open">
       <!-- This is the problem line -->
       <subfolders folder="folder"></subfolders>
    </div>
</div>

在模板中,&LT;子&GT; 只能点击此按钮触发后得到呈现 NG-IF =folder.is_open 。我猜角不知道这一点:编译指令。它进入无限循环,即使它在技术上不应该。

In the template, <subfolders> should only get rendered after the button is clicked which triggers ng-if="folder.is_open". I guess Angular does not know this when it compiles the directive. It goes into infinite loop, even though it technically should not.

有没有一种方法,使之与指导工作?其中的逻辑是在真正的应用程序稍微复杂一些,这就是为什么我在寻找,使其与指令工作。

Is there a way to make it work with the directive? The logic is a bit more complex in the real app, this is why I'm looking to make it work with the directive.

目前我使用的角度1.2.26。

I'm currently using Angular 1.2.26.

推荐答案

您可以这样做,但你需要重写指令的编译行为。你需要在编译步骤删除指令元素的内容,然后编译并在链接后步重新装上。我用下面的编译功能,取得了巨大成功:

You can do this, but you need to override the compile behavior of the directive. You need to remove contents of the directive element during the compilation step, and then compile and reattach it during the post-link step. I have used the compile function below with great success:

function compile(element) {
    var contents = element.contents().remove();
    var contentsLinker;

    return function (scope, iElement) {
        if (angular.isUndefined(contentsLinker)) {
            contentsLinker = $compile(contents);
        }

        contentsLinker(scope, function (clonedElement) {
            iElement.append(clonedElement);
        });
    };
}

我根据这个帖子,这可能是多个COM prehensive如果你需要一个pre-Link功能。

I based this function on this post, which is probably more comprehensive if you need a pre-link function.

这篇关于是否有可能引用其自身内部角定制指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆