IT

지시어 정의의 transclude 옵션을 이해하고 있습니까?

lottoking 2020. 5. 14. 08:31
반응형

지시어 정의의 transclude 옵션을 이해하고 있습니까?


나는 이것이 angularjs의 지시어로 이해하기 가장 어려운 개념 중 하나라고 생각합니다.

http://docs.angularjs.org/guide/directive 의 문서 는 다음과 같습니다.

transclude- 요소의 컨텐츠를 컴파일하고 지시문에 사용 가능하게하십시오. 일반적으로 ngTransclude와 함께 사용됩니다. transclusion의 장점은 연결 함수가 올바른 범위에 사전 바인딩 된 transclusion 함수를 수신한다는 것입니다. 일반적인 설정에서 위젯은 분리 범위를 작성하지만 변환은 하위가 아니라 분리 범위의 형제입니다. 이는 위젯이 개인 상태를 가질 수있게하고, 변환이 상위 (사전 분리) 범위에 바인딩 될 수있게합니다.

  • true-지시문의 내용을 대체합니다.
  • 'element'-낮은 우선 순위로 정의 된 지시문을 포함하여 전체 요소를 변환합니다.

그것은 말한다 transclude일반적으로 사용 ngTransclude. 그러나 ngTransclude 문서의 샘플은 ngTransclude지시문을 전혀 사용하지 않습니다 .

이것을 이해하는 데 도움이되는 좋은 예가 필요합니다. 왜 필요한가요? 무엇을 해결합니까? 사용 방법?


요소에 myDirective 라는 지시문을 고려하면 해당 요소가 다른 내용을 둘러싸고 있습니다.

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

myDirective 가 템플릿을 사용하는 경우 내용이 <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>

그래서, 당신은 유지하기 위해 무엇을하려는 경우 <button>...<a href>...는 DOM에? transclusion이라는 것이 필요합니다. 개념은 매우 간단합니다. 한 곳에서 다른 곳으로 콘텐츠를 포함합니다 . 이제 지시어는 다음과 같습니다.

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를 사용하십시오.

내 코드 예제는 여기에 있습니다 . 당신은 또한 이것을 보고 혜택을 누릴 수 있습니다 .


AngularJS의 새 버전에서 위 동작의 변경 사항을 언급하는 것이 중요하다고 생각합니다. Angular 1.2.10으로 위의 결과를 얻으려고 한 시간을 보냈습니다.

ng-transclude가있는 요소의 내용은 추가되지 않고 완전히 대체됩니다.

위의 예에서 'transclude'로 달성 한 것은 다음과 같습니다.

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

그리고 아닙니다

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

감사.


TechExplorer의 말은 사실이지만 템플릿에 ng-transclude 속성을 가진 간단한 컨테이너 태그 (div 또는 span과 같은)를 포함시켜 두 컨텐츠를 모두 가질 수 있습니다. 즉, 템플릿의 다음 코드에는 모든 내용이 포함되어야합니다.

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

위키에서 :

"컴퓨터 과학에서, 번역이란 전자 문서의 일부 또는 전부를 참조하여 하나 이상의 다른 문서에 포함시키는 것입니다."

I'd like to add another use for transclusion, and that is that it changes the execution order of the compile and link functions of parent and child directives. This can be useful when you want to compile the child DOM before the parent DOM as the parent DOM perhaps depends on the child DOM. This article goes more in depth and clarifies it very well!

http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives-part-2-transclusion/


The Updated AngularJS 1.6.6 documentation now has a better explanation.

Transclude is Used to Create a Directive that Wraps Other Elements

Sometimes it's desirable to be able to pass in an entire template rather than a string or an object. Let's say that we want to create a "dialog box" component. The dialog box should be able to wrap any arbitrary content.

To do this, we need to use the transclude option. Refer to the example below.


script.js

angular.module('docsTransclusionExample', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.name = 'Tobias';
}])
.directive('myDialog', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {},
    templateUrl: 'my-dialog.html',
    link: function(scope) {
      scope.name = 'Jeff';
    }
  };
});

index.html

<div ng-controller="Controller">
  <my-dialog>Check out the contents, {{name}}!</my-dialog>
</div>

my-dialog.html

<div class="alert" ng-transclude></div>

Compiled Output

<div ng-controller="Controller" class="ng-scope">
  <my-dialog class="ng-isolate-scope"><div class="alert" ng-transclude="">Check out the contents, Tobias!</div></my-dialog>
</div>

Transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.

This is illustrated in the previous example. Notice that we've added a link function in script.js that redefines name as Jeff. Ordinarily, we would expect that {{name}} would be Jeff. However, we see in this example that the {{name}} binding is still Tobias.

Best Practice: only use transclude: true when you want to create a directive that wraps arbitrary content.


transclude:true mean to add all element that is defined in your directive with template element of your directive.

if transclude:false the these elements are not included in your final html of directive only template of directive is rendered.

transclude:element mean your directive template is not used only element defined in your directive are rendered as html.

when you define your directive then it should be restrict to E and when you add it on page then

<my-directive><elements><my-directive>
<elements> is like <p>gratitude</p>
what i am talking about.

참고URL : https://stackoverflow.com/questions/15296284/understanding-the-transclude-option-of-directive-definition

반응형