AngularJS: 'Template for directive must have exactly one root element' when using 'th' tag in directive template

后端 未结 12 1140
梦如初夏
梦如初夏 2020-12-30 19:50

I\'m trying to implement custom sortBy directive in order to make columns in html table sortable.

HTML:


   
            


        
相关标签:
12条回答
  • 2020-12-30 20:33

    This isn't your case, but I had this very same issue because my code had html comments before and after the template markup, like so:

    <!-- Foo Widget -->
    <div class="foo-widget">[...]</div>
    <!-- end:: Foo Widget -->
    

    I got rid of the comments and voilá - problem solved.

    0 讨论(0)
  • 2020-12-30 20:33

    A more specific case of Aaron's answer is when you think that you have the correct path to the template while you actually don't: as it's stated in the documentation for the templateUrl

    The URL is relative to our index.html file

    In my case, I have placed my templates directory one level below index.html. When I was setting my property to templateUrl: '../templates/some-form.html', the path was relative to the script but not to index.html, resulting to the same error.

    0 讨论(0)
  • 2020-12-30 20:38

    This error can be also caused by the fact that you need to have a wrapping element for all your tags in the directive's template. Your directive's template can't be only:

    <nav></nav>
    <div></div>
    

    It must be:

    <div>
     <nav></nav>
     <div></div>
    </div>
    
    0 讨论(0)
  • 2020-12-30 20:39

    i encounter the following error:

    Error: [$compile:tplrt] http://errors.angularjs.org/1.2.6/$compile/tplrt?p0=stockWidget&p1=stock.html.
    

    I get around by removing commement at very top of template file.

    replace is deprecated with angularjs 1.3 forward, the next release will remove it completely, it's better not to use replace key.

    0 讨论(0)
  • 2020-12-30 20:44

    I expect that the <th> is getting melted away at some intermediate point when it is evaluated outside the context of a <tr> (put that template into some random part of your webpage to see the <th> disappear).

    In your position, I would use a <div> in the template, change sort-by-directive to an 'A' type directive, and use a <th sort-by-directive>...</th> as before, without replace: true.

    0 讨论(0)
  • 2020-12-30 20:44

    I know this is old, but there is another solution. I encountered this issue also, and tried all the above solutions with no luck.

    turns out, for some weird reason, that this error is thrown also in case there is a typo in the 'templateUrl' - if angular can't find the html file by the given path - you get the same 'must have exactly one root element' error.

    so - fixing the templateUrl fixed the error for me.

    hope this helps anyone in the future.

    0 讨论(0)
提交回复
热议问题