请任何人都可以解释为什么下面会抛出“参数'MainCtrl'不是函数,未定义”错误,该错误似乎与使用指令的模块依赖注入(inject)有关(?!)。
angular.module('app', [])
.controller('MainCtrl', [function() {
var self = this;
self.name = "will this work";
self.items = [
{
name: "name 1",
test: "test 1"
},
{
name: "name 2",
test: "test 2"
}
];
}]);
angular.module('app',[])
.directive('typeahead', [function() {
return {
templateUrl: 'type-ahead.html',
restrict: 'AEC',
scope: {
items: '=',
prompt: '@',
title: '@',
subtitle: '@',
model: '=',
onSelect: '&'
}, <...more code>
但是当我删除它时它会工作得很好
[ ]
要读取的指令中的模块依赖大括号
angular.module('app').directive('typeahead', ...)
如果我将指令定义为 Controller 定义之后的级联,它也可以正常工作,即
angular.module('app', [])
.controller('MainCtrl', [function() {
var self = this;
self.name = "will this work";
self.items = [
{
name: "name 1",
test: "test 1"
},
{
name: "name 2",
test: "test 2"
}
];
}])
.directive('typeahead', [function() {
return {
提前致谢!
最佳答案
您正在遇到 Angular 的 Creation versus Retrieval问题:
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.
第一次运行 angular.module('app',[])
时,Angular 将创建一个名为 app
的模块。下次,您只需运行 angular.module('app')
,Angular 就会尝试加载现有模块 app
。
由于您再次调用 angular.module('app',[])
,模块 app
已重新初始化。这就是为什么 MainCtrl
现在未定义。
关于javascript - 使用 angular.module 定义 angularjs 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258655/