繁体   English   中英

在 angularjs 中使用指令时出现错误 Error: [$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

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

解释

您的代码中有两个问题。

  1. 您应该关闭指令自定义元素,例如<hello-world><hello-world/> 如果您不关闭标签,第一次出现将正常工作,但之后其余部分将无法工作。 见这里
  2. 另一件事是你的指令template有错误的template

指令模板

<h3>Hello world<h3/>

应该

<h3>Hello world</h3>

您在指令中有模板,例如<h3>Hello world<h3/> ,它没有正确关闭h3标签。

所以它会在下面的页面上呈现,它有两个h3元素。

<h3>Hello world</h3>
<h3></h3>

所以渲染 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>一样将模板正确地包含在根标记中。

当使用模板(或 templateUrl)声明指令并打开替换模式时,模板必须恰好有一个根元素。 也就是说,模板属性的文本或 templateUrl 引用的内容必须包含在单个 html 元素中。 例如, <p>blah <em>blah</em> blah</p>而不是简单的blah <em>blah</em> blah 否则,替换操作将导致单个元素(指令)被多个元素或节点替换,这在实践中不受支持且通常不需要。

参考:角文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM