2015-07-12 71 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'中。 –