AngularJS错误:Template for directive 'XXXXXX'必须只有一个根元素

AngularJS error: Template for directive 'XXXXXX' must have exactly one root element

本文关键字:有一个 元素 XXXXXX directive for AngularJS 错误 Template      更新时间:2023-09-26

这是这个问题的后续

我试图建立和HTML <table>与多个<tr>行。我希望这些行中的一些由我的指令myDirectiveA渲染,其他的由我的指令'myDirectiveB'渲染。

下面你可以看到我的文件看起来像什么。如果在文件path/to/myDirectiveA.template.html中只有一行<tr>,那么一切都可以正常工作。但是,一旦我在那里添加另一行,我得到以下错误:

`angular.js:13920 Error: [$compile:tplrt] Template for directive 'myDirectiveA' must have exactly one root element. path/to/myDirectiveA.template.html`

好的,所以如果我只允许在模板文件中有一个根元素,那么我怎么能从不同的指令构造我的多行表?其他人解决这个看似常见的用例的方法是什么?

这是我的文件:

main.html:

<div ng-controller="MainCtrl as mainCtrl">
  <table width="40%" border="1">
    <tbody>
      <tr my-directive-a a="mainCtrl.a"></tr>
    </tbody>
  </table>
</div>

app.js:

myApp.directive('myDirectiveA',function(){
  return {
    'replace': true,
    'restrict': 'A',
    'scope': {
      'a': '='
    },
    'controller': 'MyDirectiveACtrl',
    'controllerAs': 'MyDirectiveACtrl',
    'bindToController': true,
    'templateUrl': "path/to/myDirectiveA.template.html"
  };
});

myApp.controller('MyDirectiveACtrl', function($scope){
    var self = this;
    $scope.$watch(function() {return {'a': self.a};}, function (objVal) {},true);
  }
);

路径//myDirectiveA.template.html:

<tr>
    <td bgcolor='#7cfc00'>MyDirectiveACtrl.a.b</td>
    <td bgcolor='#ff1493'>{{MyDirectiveACtrl.a.b}}</td>
</tr>

在应用程序中使用

<table width="40%" border="1">
  <tbody  my-directive-a a="mainCtrl.a">
  </tbody>
</table>

指令模板

<tbody>
<tr>
    <td bgcolor='#7cfc00'>MyDirectiveACtrl.a.b</td>
    <td bgcolor='#ff1493'>{{MyDirectiveACtrl.a.b}}</td>
</tr>
<tr>
    <td bgcolor='#7cfc00'>MyDirectiveACtrl.a.b</td>
    <td bgcolor='#ff1493'>{{MyDirectiveACtrl.a.b}}</td>
</tr>
</tbody>

它允许你在指令中只有一个根元素,并在其中添加多个TR。

相关文章: