javascript - 指令模板必须恰好有一个根元素 : With restrict E & replace true

标签 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 元素相关。

最佳答案

当您使用replace = true时,您的模板必须具有一个与所提到的错误完全相同的顶级元素。

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

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

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

关于javascript - 指令模板必须恰好有一个根元素 : With restrict E & replace true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29505189/

相关文章:

javascript - document.write 多行文本

javascript - Jquery,无法更新以前创建的属性

php - Code Igniter : Js file is included successfully, 脚本不工作

javascript - ng-click 不传递参数和触发器

javascript - 使用 JavaScript 简写形式连接复数或单数术语的字符串

javascript - 检测浏览器是否支持谷歌图表

c# - ASP :HiddenField get value from JavaScript Variable upon Button Click

javascript - 在 TypeScript 或 JavaScript 中过滤图像

javascript - 如何使用 angularjs 渲染 Kendo-Grid 中的数据

javascript - json 数组需要基于 angularjs 应用程序中包含时间的文本进行格式化