从另一个指令的编译函数插入指令

时间:2014-04-21 07:48:48

标签: angularjs angularjs-directive append angularjs-scope angularjs-service

我想从updater指令动态地在DOM中插入<confirmation>元素。 (我已经设置了一个事件,它在我的真实应用程序中执行)我只需要插入该元素然后它将具有相同的功能(在其各自的指令中定义)。

一些背景知识:我尝试添加元素然后使用$ compile服务 - $compile(element)(scope),但我认为指令编译函数中的$ compile不起作用。并且在没有$ compile的情况下追加它没有角度绑定。

此处已更新 Plnkr:http://plnkr.co/edit/OyBTYGTkMtxryFdDRwQN?p=preview

无论如何我能做到吗?任何帮助都会深深感激,即使它指向了正确的指示。

1 个答案:

答案 0 :(得分:1)

您不需要在compile指令中使用指令定义对象appender属性。您只需要$compile服务来编译新的<confirmation>元素 此外,您可能希望指定隔离范围的属性(即message和/或state):

.directive('appender', function ($compile) {
    return {
        restrict: 'A',
        link: function postLink(scope, elem, attrs) {
            elem.after($compile('<confirmation message="..."></confirmation>')(scope));
        }
    };
});

另请参阅此 short demo


<强>更新

根据您的评论,显然您不了解编译和链接的概念。虽然,您认为您正在使用compile属性,但事实上您只需要链接功能。我强烈建议您仔细查看关于指令定义对象的 the docs

return {
    restrict: 'A',
    link: function postLink(scope, element, attrs) {
        scope.$watch('items', function(val, oldVal) {
            if (val === oldVal) { return; }
            element.after($compile('<confirmation message="..."></confirmation>')(scope));
        }, true);
    }
};

另请参阅其他 short demo


更新2:

由于您坚持要从其他指令compile函数进行编译,所以 这是代码:

return {
    restrict: 'A',
    compile: function () {
        var compiled = $compile('<confirmation message="..."></confirmation>');
        return function postLink(scope, elem, attrs) {
            scope.$watch('items', function(val, oldVal) {
                if (val === oldVal) { return; }
                elem.after(compiled(scope));
            }, true);
        };
    }
};

这是 demo

相关问题