指令模板必须只有一个根元素:使用限制E&取代真实

时间:2015-04-08 03:02:24

标签: javascript angularjs

我目前正在维护一个传统的AngularJS应用程序(v1.3.8)。

为什么演示应用会给我以下错误?

Template for directive 'handleTable' must have exactly one root element.

sandbox.html

<!DOCTYPE html>
<html>

<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.js"></script>
<script src="sandbox.js"></script>
</head>

<body ng-app="myApp">
    <handle-table></handle-table>
</body>

</html>

sandbox.js

var app = angular.module("myApp", []);

app.directive('handleTable', function() {
    return {
        restrict: 'E',
        replace: true,
        template: 'hello world'
    };
});

报告了一个错误:Template must have exactly one root element with custom directive replace: true但是,它似乎只与table/tr/td元素相关。

1 个答案:

答案 0 :(得分:2)

当您使用replace = true时,您的模板必须只有一个顶级元素作为提到的错误。

您的角度指令模板是文本“hello world”,它不是html元素,被视为无效的根元素。

在这种情况下,您可以尝试将文本包装在span或div中:

app.directive('handleTable', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<span>hello world</span>'
    };
});