【问题标题】:Multiple directives and ng-transclude多个指令和 ng-transclude
【发布时间】:2013-08-14 12:35:39
【问题描述】:

我在对多个指令的元素使用 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>

没有被嵌入,而是被模板完全覆盖。

如何修复嵌入?

【问题讨论】:

  • 尝试 replace: false 为您的 configManaged 指令。
  • 您是否尝试在“configManaged”指令配置中使用“replace: false”?也看看这个github.com/angular/angular.js/issues/2235
  • 我尝试了'replace: false',但似乎没有什么不同。

标签: javascript angularjs angularjs-directive transclusion


【解决方案1】:

我认为您的指令不起作用。您不能在指令前加上 widget-。如果需要,可以在其前面加上 x-data-

所以&lt;div class="widget-config-modal"&gt; 不工作。

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

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

【讨论】:

  • 带有“widget-”前缀的指令似乎运行良好,问题在嵌入时更具体。
【解决方案2】:

您需要在第一个指令中创建一个ng-transclude 以包含当前内部节点&lt;div&gt; Just some div. &lt;/div&gt;。在第二个指令中,不需要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

【讨论】:

    猜你喜欢
    • 2015-05-04
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2018-01-09
    相关资源
    最近更新 更多