繁体   English   中英

angular.js:13550 TypeError:无法读取未定义的属性“编译”?

[英]angular.js:13550 TypeError: Cannot read property 'compile' of undefined?

以下 Angular js 代码抛出错误 -

“angular.js:13550 TypeError:无法读取未定义的属性'compile'”代码-

你好世界.html

 <!DOCTYPE html>
    <html ng-app="module1">
    <head>
        <title>My First Custom Directive</title>
        <script src="../angular.js"></script>
        <script src="helloworldDirective.js"></script>
    </head>
    <body>
        <hello-world></hello-world>
    </body>
    </html>

helloWorldDirective.js-

(function() {
    
    var module1=angular.module('module1',[]);
    module1.directive('helloWorld',function(){
        return
        {
            template:'Hello Somesh!!Keep it up.'
        };
        
    });
    
    
}());

但是当我用以下代码替换 Javascript 文件时,它可以工作:

(function() {
    
    var module1=angular.module('module1',[]);
    var helloWorld=function()
{
var directive={};     
directive.template='Hello Somesh!!Keep it up.';
return directive;
}
module1.directive('helloWorld',helloWorld);
    
}());

两个代码都在做基本相同的事情,但一个失败了。 有什么想法吗?

在第一个示例中,存在“无法访问的代码错误”

您可以使用以下方法修复此错误:

return template = {template: 'Hello Somesh!!Keep it up.'};

否则,您将无法获得指向该属性的指针。

JavaScript 的自动分号注入变成了这个:

  return
        {
            template:'Hello Somesh!!Keep it up.'
        };

进入这个:

  return;
        {
            template:'Hello Somesh!!Keep it up.'
        };

一个返回,后跟一个无用的代码块。 template:被视为标签。)

调试提示:JSHint 或 JSLint 会为您找到此错误。

样式提示:在 JavaScript 中,始终在同一行上保留左大括号……尽管只有returnthrow语句会受到此特定问题的影响。

使用此方法来定义您的指令:

 app.directive('helloWorld', [function () {
     return {
       restrict: 'E',
       transclude: false,
       template: 'Hello Somesh!!Keep it up.'
    }
}]);

暂无
暂无

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

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