在angularjs中使用指令时出现错误:[$compile:tplrt]

I am getting error Error: [$compile:tplrt] while using directive in angularjs

本文关键字:错误 compile tplrt angularjs 指令      更新时间:2023-09-26

在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

  1. <hello-world></hello-world>
  2. 更改指令模板以正确关闭h3标记template :'<h3>Hello world</h3>'

解释

您的代码中有两个问题。

  1. 您应该关闭像<hello-world><hello-world/>这样的指令自定义元素。如果你不关闭标签,第一次出现会很好,但之后的其他部分就不起作用了。请参见此处
  2. 另一件事是你的指令模板有错误的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