javascripthtmlangularjsangularjs-directiveangularjs-templates

AngularJS template function in directive giving error 'Template for directive must have exactly one root element'


I am working on an angular application. for a certain directive, I use the template function like this:

template: function(element, attr) {
              return '<div class="myClass">/..some HTML here../</div>'
          }

However, when I run my code, I get the following error:

Error: Template for directive must have exactly one root element, was function (element, attr) { ...the function definition goes here }

If I change it to normal key value pair as follows, it works fine.

template: '<div class="myClass">/..some HTML here../</div>'

I don't understand what's wrong here. The link and compile functions work just fine. Any help on this would be really appreciated. Thanks in advance


Solution

  • This feature was introduced in a later version of angular 1.1.4. You'll have to upgrade or find a workaround as @saiyan mentioned.

    Check this plunkr - plnkr.co/edit/QVdE3xdn3hmcoQ33gj2R?p=preview

    HTML:

    <!DOCTYPE html>
    <html ng-app="myapp">
    
       <head>
    
        <!-- CHANGE THE ANGULAR VERSION HERE  -->
        <script src="https://code.angularjs.org/1.0.4/angular.js"></script>
    
        <script src="app.js"></script>
      </head> 
    
      <body >
        <div something></div>
      </body>
    
    </html>
    

    JS:

    var app = angular.module('myapp', []);
    
    app
        .directive("something", function () {
            return {
                template: function () {
                    return "Hello World!";
                }
            }
        })