在angularjs中使用指令时出现错误:[$compile:tplrt]
I am getting error Error: [$compile:tplrt] while using directive in angularjs
在angularJS 1.3.14中
var app = angular.module('myApp',[]);
app.controller('myController',['$scope',function($scope){
$scope.name = 'world';
}]);
//here i created directive of name helloWorld
app.directive('helloWorld',function(){
return {
replace:true,
restrict:'AE',
template :'<h3>Hello world<h3/>'
}
});
<html ng-app='myApp'>
<body ng-controller = "myController">
<hello-world/>
</body>
</html>
错误为:
错误:[$compile:tplrt]指令"helloWorld"的模板必须具有正好是一个根元素。
如何解决此错误?
快速修复
根本原因(replace: true
)
<hello-world></hello-world>
- 更改指令模板以正确关闭
h3
标记template :'<h3>Hello world</h3>'
解释
您的代码中有两个问题。
- 您应该关闭像
<hello-world><hello-world/>
这样的指令自定义元素。如果你不关闭标签,第一次出现会很好,但之后的其他部分就不起作用了。请参见此处 - 另一件事是你的指令模板有错误的
template
指令模板
<h3>Hello world<h3/>
应该是
<h3>Hello world</h3>
指令中的模板,如<h3>Hello world<h3/>
,没有正确关闭h3
标记。
因此,它在如下页面上呈现,该页面有两个h3
元素。
<h3>Hello world</h3>
<h3></h3>
所以render html有两个单独的元素。因此,在将它们传递给$compile
服务以编译模板的内容时,它抛出了[$compile:tplrt]
,这意味着你的模板应该有一个根元素,所以angular将编译该元素。
注释替换:true。
var app = angular.module('myApp',[]);
app.controller('myController',['$scope',function($scope){
$scope.name = 'world';
}]);
//**here i created directive of name helloWorld**
app.directive('helloWorld',function(){
return {
restrict:'AE',
//replace:true,
template :'<h3>Hello world<h3/>'
};
});
or
//**here i created directive of name helloWorld**
app.directive('helloWorld',function(){
return {
restrict:'AE',
replace:true,
template :'<div><h3>Hello world<h3/></div>'
};
});
您收到错误是因为在您的指令中您使用的是replace:true
,并且模板包含在h3
中。标签绞车未正确关闭(您应该使用</h3>
而不是<h3/>
关闭h3
标签)。
您应该像<h3>Hello world</h3>
一样将模板适当地包含在根标记中。
当使用template(或templateUrl)和如果启用替换模式,则模板必须只有一个根元素。那个是模板属性的文本或templateUrl必须包含在单个html元素中。对于例如
<p>blah <em>blah</em> blah</p>
而不是简单的blah <em>blah</em> blah
。否则,将导致更换操作在单个元素(指令)中替换为多个元素或节点,在实践
参考:Angular Docs
相关文章:
- 错误:[$compile:nonassign]表达式'未定义'与指令'内容可编辑'是不可
- Ember 1.10-升级错误-模板必须是一个函数.您是想调用Ember.Handlebars.compile(“..”
- 未捕获错误:在未加载模板编译器的情况下,无法调用“compile”.请在调用“compile”之前加载“ember te
- Angular ngRoute可以't加载模板:错误[$compile:tpload]
- 使用 Angular.js 使用多选下拉列表时出现 [$compile:multidir] 错误
- 错误:[$compile:multidir] 将 md-sidenav 与控制器(角度材料)绑定时
- 错误:找不到指令 所需的 [$compile:ctreq] 控制器
- 引用错误可以'找不到变量$compile
- 在angularjs中使用指令时出现错误:[$compile:tplrt]
- 错误:[$compile:multer]多个指令[mdVirtualRepeat,ngInclude]要求进行trans
- 收到错误: [$compile:multidir] 使用 Angular.js
- 错误:[$compile:nonassign]表达式'未定义'与指令'myFacebook
- Angularjs:错误:[$compile:ctreq] Controller 'carousel',
- 错误:$compile:tpload未能加载模板Http状态:404
- 错误:[$compile:tplrt]指令'checknav 39;必须只有一个根元素
- 添加ng重复导致错误:$compile:ctreq
- 角度.js:13642 错误: [$compile:多目录].
- 错误:$compile:ctreq缺少所需的控制器
- Angular js错误:[$compile:ctreq]指令yyyy要求的控制器xxxx,无法找到
- Ng-change抛出错误[$compile:ctreq]