angularJs directive template removal

1.2k views Asked by At

in every angular template we have to define a root html node, then inside it we can define the Html of our directive.

is there a way in angular to ignore that root node? example :

my directive template :

<div class="space consuming div, and absolute positioning breaker"> 
   <div class="content positioned relative to the directives parent 1"></div>
   <div class="content positioned relative to the directives parent 2"></div>
   <div class="content positioned relative to the directives parent 3"></div>
</div>

can we just set our template to be

   <div class="content positioned relative to the directives parent 1"></div>
   <div class="content positioned relative to the directives parent 2"></div>
   <div class="content positioned relative to the directives parent 3"></div>

thanks!

1

There are 1 answers

0
musically_ut On

You only need one root element if you are using replace: true in your template.

This is the case if you have defined custom element and are using then in your HTML in the following way:

<tabs>
    <pane>1</pane>
    <pane>2</pane>
</tabs>

In this case, replacing tabs with a template which has two roots will cause some confusion.

However, if you do not need replace: true, then you can set the directive on the element you want and assign a multi-root template on it. That template will be rendered inside the element which has the directive.

JS

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

app.directive('myDirectiveOne', function() {
  return {
    template: '<p>Hello</p><p>World!</p>'
  };
})


app.directive('myDirectiveTwo', function() {
  return {
    template: '<p>Hello</p><p>World!</p>',
    replace: true
  };
})

Template

    <!-- works -->
    <div my-directive-one></div>

    <!-- has problem -->
    <div my-directive-two></div>

E.g. http://plnkr.co/edit/jgEWsaxzfD4FkHcocJys?p=preview