AngularJS错误:指令'XXXXXX'的模板必须只有一个根元素 [英] AngularJS error: Template for directive 'XXXXXX' must have exactly one root element

查看:628
本文介绍了AngularJS错误:指令'XXXXXX'的模板必须只有一个根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 此问题

我正在尝试构建HTML < table> 包含多个< tr> 行。我希望其中一些行可以通过我的指令 myDirectiveA 呈现,而其他行则由我的指令'myDirectiveB'呈现。

I am trying to build and HTML <table> with multiple <tr> rows. I want some of these rows to be rendered by my directive myDirectiveA and others to be rendered by my directive 'myDirectiveB'.

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

Below you can see what my files look like. It all works fine if there is only one <tr> row in the file path/to/myDirectiveA.template.html. But as soon as I add another row in there, I get the following error:

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

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

Ok, so if I am allowed only to have one root element in that template file, then how can I construct my table with multiple rows from various directives? What is the way other people solve this seemingly-common use-case?

以下是我的文件:

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

It allows you to have only one root element in your directive, and add more than one TR inside of it.

这篇关于AngularJS错误:指令'XXXXXX'的模板必须只有一个根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆