模板必须只有一个带有自定义指令replace的根元素:true

Rya*_*sch 12 angularjs angularjs-directive

我遇到了一个带有replace的自定义指令的问题:true,

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

据我所知,我只有一个根元素,我的,这里发生了什么?

Error: Template must have exactly one root element. was: 
<tbody>
  <tr><td>{{ item.name }}</td></tr>
  <tr><td>row2</td></tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)

使用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'
    }
  ];
}]);
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Cai*_*nha 19

似乎是AngularJs 的已知错误.

您可以做的是将限制更改为属性而不是元素,tbody从模板中删除并<tbody custom ng-repeat="item in items">在您的HTML代码中使用a .

基本上:

您的模板变为:

<tr><td>{{ item.name }}</td></tr>
<tr><td>row2</td></tr>
Run Code Online (Sandbox Code Playgroud)

你的指令:

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

  }
};
Run Code Online (Sandbox Code Playgroud)

你的HTML:

<div data-ng-controller="MyCtrl">
  <table>
    <tbody custom data-ng-repeat="item in items"></tbody>
  </table>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 这给你提供了与物品一样多的tbody元素. (9认同)