Understanding the transclude option of directive definition? Ask Question

Understanding the transclude option of directive definition? Ask Question

I think this is one of the hardest concept for me to understand with angularjs's directive.

The document from http://docs.angularjs.org/guide/directive says:

transclude - compile the content of the element and make it available to the directive. Typically used with ngTransclude. The advantage of transclusion is that the linking function receives a transclusion function which is pre-bound to the correct scope. In a typical setup the widget creates an isolate scope, but the transclusion is not a child, but a sibling of the isolate scope. This makes it possible for the widget to have private state, and the transclusion to be bound to the parent (pre-isolate) scope.

  • true - transclude the content of the directive.
  • 'element' - transclude the whole element including any directives defined at lower priority.

It says transclude typically used with ngTransclude. But the sample from the doc of ngTranscludengTranscludeディレクティブをまったく使用しません。

これを理解するのに役立つ良い例がいくつか欲しいです。なぜそれが必要なのでしょうか? 何を解決するのでしょうか? どのように使用するのでしょうか?

ベストアンサー1

という指令を考えてみましょうマイディレクティブ要素内に他のコンテンツが含まれているとします。

<div my-directive>
    <button>some button</button>
    <a href="#">and a link</a>
</div>

もしマイディレクティブ<div my-directive>テンプレートを使用している場合、 の内容がディレクティブテンプレートに置き換えられることがわかります。つまり、

app.directive('myDirective', function(){
    return{
        template: '<div class="something"> This is my directive content</div>'
    }
});

次のようなレンダリング結果になります:

<div class="something"> This is my directive content</div> 

元の要素の内容に注目してください<div my-directive> 失うだろう(あるいは、置き換えられたと言うべきでしょう)。それでは、これらの仲間たちに別れを告げましょう:

<button>some button</button>
<a href="#">and a link</a>

では、 DOM 内に<button>...and を保持したい場合はどうすればよいでしょうか。トランスクルージョンと呼ばれるものが必要になります。その概念は非常にシンプルです。<a href>...ある場所のコンテンツを別の場所に含める. これで、ディレクティブは次のようになります。

app.directive('myDirective', function(){
    return{
        transclude: true,
        template: '<div class="something"> This is my directive content</div> <ng-transclude></ng-transclude>'
    }
});

次のように表示されます:

<div class="something"> This is my directive content
    <button>some button</button>
    <a href="#">and a link</a>
</div>. 

結論として、ディレクティブを使用しているときに要素の内容を保持したい場合は、基本的に transclude を使用します。

私のコード例はここ視聴することでもメリットがありますこれ

おすすめ記事