2015-07-12 72 views
1

所以,我有这个代码使用角度transclude嵌套ng-transclude角

angular.module('playground', []).directive('tagA', function() { 
     return { 
      replace: true, 
      transclude: true, 
      controller: function() { 
       console.log('controller tagA') 
      }, 
      compile: function($element, $attrs, $link) { 
       console.log('compile tagA', $element.html()); 
       return { 
        pre: function($scope, $element, $attrs, controller, $transclude) { 
         console.log('pre tagA', $element.html()); 
        }, 
        post: function($scope, $element, $attrs, controller, $transclude) { 
         console.log('post tagA', $element.html()); 
        } 
       } 
      }, 
      template: '<u><tag-b><div ng-transclude></div></tag-b></u>' 
     } 
    }).directive('tagB', function() { 
     return { 
      require: '^tagA', 
      transclude: true, 
      controller: function() { 
       console.log('controller tagB') 
      }, 
      compile: function($element, $attrs, $transclude) { 
       console.log('compile tagB', $element.html()); 
       return { 
        pre: function($scope, $element, $attrs, controller, $transclude) { 
         console.log('pre tagB', $element.html()); 
        }, 
        post: function($scope, $element, $attrs, controller, $transclude) { 
         console.log('post tagB', $element.html()); 
        } 
       } 
      }, 
      template: '<h1 ng-transclude></h1>' 
     } 
    }); 

而且标记

<tag-a> 
    Test 
</tag-a> 

我所试图做的是从父(塔加)的transcluded内容传递给孩子(TAGB)。上面的代码有效,但我不想在我的tagA的模板中有<div ng-transclude></div>。显然,使用<u><tag-b ng-transclude></tag-b></u>不起作用。 (<u><tag-b ng-transclude></tag-b></u>)不能工作吗?

+0

后者的方式不起作用,因为transclude替换内部HTML,所以它会取代元素,以及'NG-transclude'将不再是内部元件上。 – Claies

回答

1

后一种形式不起作用,因为transclude取代了放置在ng-transclude上的元素的内部HTML。

在第一个,(工作您有类似以下):

<tag-a> 
    <u> 
    <tag-b> 
     <div ng-transclude> 
     <h1 ng-transclude> 
      Test 
     </h1> 
     </div> 
    </tag-b> 
    </u> 
</tag-a> 

由于内的HTML被替换,你最终得到的是:

<u> 
    <div> 
    <h1> 
     Test 
    </h1> 
    <div> 
</u> 

在第二个例子,你有:

<tag-a> 
    <u> 
    <tag-b ng-transclude> 
     <h1 ng-transclude> 
     Test 
     </h1> 
    </tag-b> 
    </u> 
</tag-a> 

再次,与指令删除和内部的html替换,你会得到:

<u> 
</u> 
+0

我认为对于工作形式,我的最终HTML是'u> tag-b> h1> div> span'。这意味着'div'不会被替换/移除,而是将被移过的内容('span')放在'div'中。 –