AngularJS错误:指令模板' XXXXXX'必须只有一个根元素

时间:2016-09-25 04:52:56

标签: javascript html angularjs html-table angular-directive

这是this question的后续行动。

我正在尝试使用多个<table>行构建和HTML <tr>。我希望其中一些行由我的指令myDirectiveA呈现,而其他行则由我的指令&#39; myDirectiveB&#39;呈现。

下面你可以看到我的文件是什么样的。如果文件<tr>中只有一个path/to/myDirectiveA.template.html行,则一切正常。但是当我在那里添加另一行时,我收到以下错误:

`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>

1 个答案:

答案 0 :(得分:2)

在应用中使用此功能

<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。