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

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

以下Angularjs代码抛出错误-

"angular.js:13550 TypeError: Cannot read property 'compile' of undefined" for the code-

HelloWorld.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);
    
}());

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

在第一个例子中,有一个"unreachable code error"

您可以通过以下方式修复此错误:

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

否则无法获取指向属性的指针。

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

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

进入这个:

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

a return,后跟无用的代码块。 (template: 被视为标签。)

调试提示:JSHint 或 JSLint 会为您发现此错误。

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

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

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