多个指令和ng-transclude

时间:2013-08-14 12:35:40

标签: javascript angularjs angularjs-directive transclusion

我在使用ng-transclude对多个指令的元素时遇到问题。

我有两个指令,其中一个实例化另一个:

//Basic first directive, checks if the second should be instantiated
app.directive('configModal', ['$compile', function($compile){
    return {
        restrict: 'C',
        scope: {
            manage: '=manage',
        },
        controller: function($scope, $element, $attrs, $transclude) {
            //used to instantiate the second directive which is 'C' restricted
            $element.addClass('widget-config-managed');
            $compile($element);
            };
        }
    };
}]);

//Second directive, has two wrap the content of the element by transclusion
app.directive('configManaged', ['$compile', function($compile){
    return {
        restrict: 'C',
        template: '<div ng-transclude>Some more content</div>',
        transclude: true,
        compile: function(element){
            console.log('compile from managed');
        }
    };
}]);

HTML看起来像这样:

<div class="widget-config-modal">
<div>
    Just some div.
</div>

问题在于div的原始内容:

    <div>
        Just some div.
    </div>

不会被转录,但会被模板完全覆盖。

如何修复转换?

2 个答案:

答案 0 :(得分:0)

我不认为你的指令是有效的。您不能在指令前添加widget-前缀。如果您愿意,可以使用x-data-

作为前缀

所以<div class="widget-config-modal">不行。

相反,您可以执行以下操作:

<div class="config-modal">
<!-- OR -->
<div class="data-config-modal">
<!-- OR -->
<div class="x-config-modal">

答案 1 :(得分:0)

您需要在第一个指令中创建ng-transclude以包含当前内部节点<div> Just some div. </div>。在第二个指令中,不需要ng-transclude

configModal

transclude: true,
template: '<div><div ng-transclude></div><div class="config-managed"></div></div>'

configManaged

template: '<div>Some more content</div>'

Demo