Shawn Shawn - 2 months ago 14
AngularJS Question

AngularJS - how to include a template without a wrapper

For example I have a template like the following.

template.html:

<div>div1</div>
<div>div2</div>


I want to include it anywhere I want without a wrapper, so the result is like this:

<body>
.
.
<div>div1</div>
<div>div2</div>
.
.
</body>


I can't use
ng-include
because it has a wrapper
<ng-include>
.

I tried creating a directive with
replace:true
, but an error says the template must have only one root element.

If it is a comment directive without
replace:true
, then the template won't show.

What should I do? I need this because a wrapper will mess up the layout.

Answer

try this:

app.directive('i', ['$interpolate', function($interpolate) {
  return {
    scope: {
      i: '<'
    },
    template: '<div>{{ i.text1 || \'DIV1\' }}</div><div>{{ i.text2 || \'DIV2\' }}</div>',
    link: function (scope, element, attrs) {
      element.after($interpolate(element.html())(scope));
      element.remove();
    }
  };
}]);

here is plunker http://plnkr.co/edit/hRHMcvTfC2BNETO64SnW?p=preview

you can pass text variables to be printed, if not passed - devault 'DIV1' and 'DIV2' will be printed

Comments