Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

AngularJS : transcluding multiple sub elements in a single Angular directive

I was reading about ng-transclude in the AngularJS docs on Creating a Directive that Wraps Other Elements and I think I understand properly what it does.

If you have a directive that applies to an element that has content inside it such as the following:

<my-directive>directive content</my-directive>

it will allow you to tag an element within the directive's template with ng-transclude and the content included in the element would be rendered inside the tagged element.

So if the template for myDirective is

<div>before</div>
<div ng-transclude></div>
<div>after</div>

it would render as

<div>before</div>
<div ng-transclude>directive content</div>
<div>after</div>

My question is if it is possible to somehow pass more then a single block of html into my directive?

For example, suppose the directive usage would look like this:

<my-multipart-directive>
     <part1>content1</part1>
     <part2>content2</part2>
</my-multipart-directive>

and have a template like:

<div>
  this: <div ng-transclude="part2"></div>
   was after that: <div ng-transclude="part1"></div>
   but now they are switched
<div>

I want it to render as follows:

<div>
  this: <div ng-transclude="part2">content2</div>
   was after that: <div ng-transclude="part1">content1</div>
   but now they are switched
<div>

Perhaps I could somehow bind the HTML value of a node to the model so that I will be able to use it in such a way without calling it "transclude"?

question from:https://stackoverflow.com/questions/22079587/angularjs-transcluding-multiple-sub-elements-in-a-single-angular-directive

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

1 Reply

0 votes
by (71.8m points)

Starting Angular 1.5, it's now possible to create multiple slots. Instead of transclude:true, you provide an object with the mappings of each slot:

https://docs.angularjs.org/api/ng/directive/ngTransclude

angular.module('multiSlotTranscludeExample', [])
 .directive('pane', function(){
    return {
      restrict: 'E',
      transclude: {
        'title': '?pane-title',
        'body': 'pane-body',
        'footer': '?pane-footer'
      },
      template: '<div style="border: 1px solid black;">' +
                  '<div class="title" ng-transclude="title">Fallback Title</div>' +
                  '<div ng-transclude="body"></div>' +
                  '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
                '</div>'
    };
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...