What is ng-transclude?

后端 未结 3 2024
情书的邮戳
情书的邮戳 2020-12-02 04:07

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

相关标签:
3条回答
  • 2020-12-02 04:16

    For those who come from React world, this is like React's {props.children}.

    0 讨论(0)
  • 2020-12-02 04:21

    it's a kind of yield, everything from the element.html() gets rendered there but the directive attributes still visible in the certain scope.

    0 讨论(0)
  • 2020-12-02 04:28

    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

    Visualize :

    0 讨论(0)
提交回复
热议问题