AngularJS指令出错-无法读取属性'编译'的未定义
AngularJS directives erroring out - Cannot read property 'compile' of undefined
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;}});
相关文章:
- 为什么“;未定义的“;在JavaScript中结束循环
- 要求未定义JS回调参数
- 如何检查管道中未定义的项目
- TypeError:无法读取属性'推'未定义的JavaScript
- $window.ga在AngularJS事件中未定义
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 无法获取属性'selectedIndex'的未定义引用或null引用
- 如何消除代码中的未定义和其他问题
- 未捕获的ReferenceError:$未定义
- this.router在AngularJS 2中未定义
- AngularJS指令出错-无法读取属性'编译'的未定义
- 无法读取属性'编译'的未定义.可以'我似乎没有发现错误
- AngularJS$scope在指令中编译控制器时未定义
- 正在修复将其编译为未定义的
- 榆树早午餐编译问题:“拆分”未定义
- Babel 编译 es6 类,函数未定义
- 运行rake资产预编译后,得到未定义的不是一个函数
- Handlebars预编译模板返回未定义的值
- 在babel编译之后,MomentJS return global是未定义的