The directive (nested inside partial) throws "The terminal must have exactly one root element"

I try to follow angular's best practice guidelines and use directives to encapsulate reusable HTML elements. Error message:

Error: the template must have exactly one root element. was: partials / user / path / to / somedata.html

directive code:

.directive('stDirectivename', function() { return { restrict: 'E', replace: true, // transclude: false, template: 'partials/user/path/to/somedata.html' }; }) 

And the template:

 <div ng-show="person.condition" class="someclass"> <span class = "personRoi"> <i class="anotherclass " ng-class="{'specialclass1': person.count>=0,'specialclass2':person.count<0}"> </i>{{person.somedata}}% </span> </div> 

Called in partial (which is a modal pattern) as:
<st-directivename></st-directivename>

when i replace url template for plain html line in directive. Everything works. Unfortunately, I cannot do this for a real template that includes both ' and.' In addition, this solution will not scale for larger templates that I plan for some directives.

Also, when I just insert the html template instead of the directive tag, everything works correctly (I actually extract the code from the existing html to make it reusable).

I read in other SO questions that this is related to adding extra space / tags / comments in the template. But I can not find such elements.

Does anyone know a solution for this? I will be happy for any help.

+7
angularjs angularjs-directive
source share
3 answers

Your mistake: you should use templateUrl and not template to indicate the path to the partial html part

 .directive('stDirectivename', function(){ return { restrict:'E', replace:true, //transclude:false, templateUrl:'partials/user/path/to/somedata.html' }; }) 
+6
source share

For those who may come after this, also note that the directive templates should have - and the error says - only one root element, that is, many intervals or divs should be enclosed in the root div.

Also pay attention to comments on OP: spaces or trailing comments in the template can also lead to this error.

It seems that the fix to make Angular less temperamental in this could be included in the next version / update: github.com/angular/angular.js/issues/1459

+6
source share

For those who are still looking for additional hints ... I encountered the same error when I had a typo in the templateUrl directive path. You will get this error if you have replaced: true . Otherwise, you might see a wilder error like WARNING: Tried to load angular more than once , and it took me a while to figure out, because the error message is really misleading.

+2
source share

All Articles