Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template must have exactly one root element with custom directive replace: true

I am having issues with a custom directive with replace: true,

http://jsbin.com/OtARocO/2/edit

As far as I can tell, I do only have one root element, my , what is going on here?

Error: Template must have exactly one root element. was: 
<tbody>
  <tr><td>{{ item.name }}</td></tr>
  <tr><td>row2</td></tr>
</tbody>

Javascript:

var app = angular.module("AngularApp", [])
  .directive('custom', [function () {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'lineItem.html',
      link: function(scope, element, attrs) {

      }
    };
  }])
.controller('MyCtrl', ['$scope', function($scope) {
  $scope.items = [
    { 
      name: 'foo'
    },
    {
      name: 'bar'
    },
    {
      name: 'baz'
    }
  ];
}]);

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
  <meta name="description" content="Angular Avatar Example" />  

  <script src="//crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>


<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body data-ng-app="AngularApp">
  <script type="text/ng-template" id="lineItem.html">
    <tbody>
      <tr><td>{{ item.name }}</td></tr>
      <tr><td>row2</td></tr>
    </tbody>
  </script>
  <div data-ng-controller="MyCtrl">
    <table>
      <custom data-ng-repeat="item in items"></custom>
    </table>
  </div>
</body>
</html>
like image 972
RyanHirsch Avatar asked Oct 07 '13 19:10

RyanHirsch


1 Answers

Seems to be a known bug of AngularJs.

What you could do is to change the restriction to attribute instead of element, remove the tbody from the template and use a <tbody custom ng-repeat="item in items"> in your html code.

Basically:

Your template becomes:

<tr><td>{{ item.name }}</td></tr>
<tr><td>row2</td></tr>

Your directive:

return {
  restrict: 'A',
  templateUrl: 'lineItem.html',
  link: function(scope, element, attrs) {

  }
};

And your HTML :

<div data-ng-controller="MyCtrl">
  <table>
    <tbody custom data-ng-repeat="item in items"></tbody>
  </table>
</div>
like image 185
Caio Cunha Avatar answered Oct 12 '22 13:10

Caio Cunha