在添加指令时,Controller是未定义的

Angular: Controller is undefined when adding a directive

本文关键字:未定义 Controller 添加 指令      更新时间:2023-09-26

我得到以下错误时,添加一个指令到我的网站:

Error: [ng:areq] Argument 'MainController' is not a function, got undefined

只有当我在我的站点中包含welcome-directive (welcome.js)时才会出现错误。如果导入被移除,说明控制器工作

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

angular.module('my-app', [])
  .controller('MainController', ['$scope', function($scope) {
    console.log('Controller working');
  }]);

welcome.js

angular.module('my-app', [])
  .directive("welcome", function() {
    return {
      restrict: "E",
      template: "<div>Test test.</div>"
    };
  });

您正在重新定义模块。只定义一次模块

作为angular.module('my-app', [])使用时,它定义了只应该使用一次的模块。当你想取回它的时候。然后使用angular.module('my-app')

使用

angular.module('my-app')  //Notice remove []
  .directive("welcome", function() {
  });

像这样传递第二个参数angular.module('my-app', [])创建一个新模块,只使用一次。

要检索模块使用var module = angular.module('my-app')和使用module.controller(...module.directive(....等,