我目前正在维护一个遗留的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>'
};
});