指令的模板必须只有一个根元素:With restrict E&替换true

Template for directive must have exactly one root element : With restrict E & replace true

本文关键字:restrict With amp true 替换 元素 有一个 指令      更新时间:2023-09-26

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

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

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

沙盒.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>

沙盒.js

var app = angular.module("myApp", []);
app.directive('handleTable', function() {
    return {
        restrict: 'E',
        replace: true,
        template: 'hello world'
    };
});

报告了一个错误:Template必须有一个带有自定义指令replace:true的根元素。然而,它似乎只与table/tr/td元素有关。

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

您的angular指令模板是文本"helloworld",它不是html元素,被视为无效的根元素。

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

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