AngularJS指令出错-无法读取属性'编译'的未定义

AngularJS directives erroring out - Cannot read property 'compile' of undefined

本文关键字:编译 未定义 属性 读取 出错 指令 AngularJS      更新时间:2023-09-26

AngularJS新手,并试图创建一个简单的指令。代码失败,返回TypeError:无法读取未定义的属性"compile"。如有任何建议,我们将不胜感激。

JS

var xx = angular.module('myApp', []);
xx.directive('myFoo', 
             function(){
                 return 
                 {
                     template:'23'
                 };                     
});

HTML

<div ng-app="myApp">
<div my-foo></div>
</div>

你可以在这里找到代码和错误https://jsfiddle.net/p11qqrxx/15/

这只是您的返回语句。

错误:

return 
{} // This returns undefined, return is odd and doesn't look at the next line

好:

return{
} // Returns an empty object, always open your object on the same line as the return

更好:

var directive = {};
return directive; // How I always do it, to avoid the issue.

这不是Angular的问题,而是编写和执行javascript返回语法的方式。我制作了一个简单的视频,更详细地演示了这个问题。你可以从这个链接看到这个视频。

https://www.facebook.com/shivprasad.koirala/videos/910570055693818/

现在是长答案。在javascript中,"return"answers"return;"是相同的,"{}"是一个匿名函数。

当你在下一行写return和"{"时,它的两个语句一个返回,"{}"是一个匿名函数。程序从"return"语法返回,并且花括号内的代码从未执行过,或者我们可以说这是一个无法访问的代码。所以它返回"未定义"。

return  // returns from this step itself
{
  // any code here will never execute
 // unreachable code
}

当您在返回语句之后编写花括号时,它会将它们视为一个代码块,并执行花括号内的代码。

return{
// any code here will execute
}

所以这一切都是关于你的花括号在return语句后面的位置。

您还提到了AngularJs 1.0.0,它太旧了,我将其更新为1.1

将指令更改为此

xx.directive('myFoo',
function () {
    return {
        restrict: 'A', //defaults its A no need of it to declare.
        template: '23'
    };
});

工作Fiddle

xx.指令('myFoo',

函数(){var对象={restrict:"A",//默认为其A,无需声明。模板:"23"返回obje;}});