What is the main use of transclusion in angularjs

对着背影说爱祢 提交于 2019-12-06 08:47:30

问题


I have recently come across transclusion in directives, what is the purpose of having this concept. As far as I know its encapsulation of an object and have 2-way binding possibly. But this can be possible by using '=' in the scope attribute in directive. So whats the big deal about directive?


回答1:


Transclude allows :

  • To create directives that wrap other elements.
  • To clone the same transcluded contents multiple times.
  • To re-clone the trancluded contents when an event occurs.

ngTransclude and $transclude

  • When using the transclude option, the element contents are being removed from the DOM during the compile phase.
  • The 5th argument of the linking phase ( or $transclude inside directive controllers ) is a $transclude function which allows you to clone the transcluded contents , apply it to a scope and reinsert it to the DOM when you need.
  • Angular.js has a built-in directive for simple cases: ngTransclude

I recommend these tutorials:

  • Angular.js - Transclusion basics
  • Angular.js - Components and containers

Some angular built-in directives (ng module) use the transclude option:

  • ngIf
  • ngInclude
  • ngRepeat
  • ngSwitch

In the docs

What does transclude option do? it makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.

Actually, that's not so accurate, it applies only to the default behavior of angular.js built-in directives and the default behavior of the $transclude function when invoked without scope argument.

The $transclude function allows you to apply any scope you need as an optional first argument:

app.directive('example',function(){
  return {
    transclude: true,
    template: "<div>example</div>"
    link: function (scope, element, attrs, ctrl, $transclude){
      $transclude(scope, function(clone){
        element.append(clone);
      })
    }
  }
})



回答2:


My main use is to relocate the inner contents of a directive to wherever the ngTransclude is inside the template of the directive.

http://plnkr.co/edit/aQ7SG58g0njSerM8FsNz?p=preview

var app = angular.module('myApp', []);

app.directive('wrapMe', [function () {
  return {
    restrict: 'E',
    transclude: true,
    template: '<span>Stuff before [<b ng-transclude></b>] Stuff after</span>'
  };  
}]);


来源:https://stackoverflow.com/questions/21087717/what-is-the-main-use-of-transclusion-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!