What is the main use of transclusion in angularjs

岁酱吖の 提交于 2019-12-04 13:10:19

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:

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

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);
      })
    }
  }
})

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