Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

angularjs - What is ng-transclude?

I have seen a number of questions on StackOverflow discussing ng-transclude, but none explaining in layman's terms what it is.

The description in the documentation is as follows:

Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.

This is fairly confusing. Would someone be able to explain in simple terms what ng-transclude is intended to do and where it might be used?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Transclude is a setting to tell angular to capture everything that is put inside the directive in the markup and use it somewhere(Where actually the ng-transclude is at) in the directive's template. Read more about this under Creating a Directive that Wraps Other Elements section on documentation of directives.

If you write a custom directive you use ng-transclude in the directive template to mark the point where you want to insert the contents of the element

angular.module('app', [])
  .directive('hero', function () {
    return {
      restrict: 'E',
      transclude: true,
      scope: { name:'@' },
      template: '<div>' +
                  '<div>{{name}}</div><br>' +
                  '<div ng-transclude></div>' +
                '</div>'
    };
  });

If you put this in your markup

<hero name="superman">Stuff inside the custom directive</hero>

It would show up like:

Superman

Stuff inside the custom directive

Full example :

Index.html

<body ng-app="myApp">
  <div class="AAA">
   <hero name="superman">Stuff inside the custom directive</hero>
</div>
</body>

jscript.js

angular.module('myApp', []).directive('hero', function () {
    return {
      restrict: 'E',
      transclude: true,
      scope: { name:'@' },
      template: '<div>' +
                  '<div>{{name}}</div><br>' +
                  '<div ng-transclude></div>' +
                '</div>'
    };
  });

Output markup

enter image description here

Visualize :

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...