问题描述
向我的网站添加指令时出现以下错误:
I get the following error when adding a directive to my site:
Error: [ng:areq] Argument 'MainController' is not a function, got undefined
仅当我在网站中包含welcome-directive(welcome.js)时,才会发生错误.如果导入被删除,则控制器可以正常工作.
The error only occurs when I include the welcome-directive (welcome.js) in my site. If the import is removed the controller works.
我的index.html正文
Body of my index.html
<body ng-app="my-app">
<div ng-controller="MainController">
<welcome></welcome>
</div>
<!-- Angular -->
<script src="bower_components/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/mainController.js"></script>
<!-- Without this line the controller works -->
<script src="js/directives/welcome.js"></script>
</body>
app.js
(function() {
var app = angular.module('my-app', []);
})();
mainController.js
mainController.js
angular.module('my-app', [])
.controller('MainController', ['$scope', function($scope) {
console.log('Controller working');
}]);
welcome.js
welcome.js
angular.module('my-app', [])
.directive("welcome", function() {
return {
restrict: "E",
template: "<div>Test test.</div>"
};
});
推荐答案
您正在重新定义模块.只需定义一次模块.
You are redefining the module. Define module only once.
当用作angular.module('my-app', [])
时,它定义了该模块,该模块只能使用一次.当您想要检索它时.然后使用angular.module('my-app')
when used as angular.module('my-app', [])
it defined the module this should be used only once. When you want retrieve it. then use angular.module('my-app')
使用
angular.module('my-app') //Notice remove []
.directive("welcome", function() {
});
这篇关于Angular:添加指令时未定义控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!