Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directive (nested inside a partial) throws “Termplate must have exactly one root element”

I'm trying to follow angular best practice recommendation and use directives to encapsulate reusuable HTML elements. The error message:

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

the 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 the partial (which is the template of a modal) as:
<st-directivename></st-directivename>

when I replace the template url for a simple html string in the directive. Everything works. Unfortunately I can't do that for the real template that involves both ' and. besides this solution won't scale to the larger templates I plan to some directives.

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

I read in other SO questions that this has to do with having extra space/tags/comments in the template. But I just can't find such elements.

Does anybody know a solution for this? I'll be glad for any help.

like image 887
alonisser Avatar asked Oct 30 '13 07:10

alonisser


1 Answers

your mistake is: you must use templateUrl rather than template so as to indicate the path to the html partial

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

    };
})
like image 87
Stephane Rolland Avatar answered Sep 22 '22 13:09

Stephane Rolland