【问题标题】:Angular: Controller is undefined when adding a directiveAngular:添加指令时未定义控制器
【发布时间】:2017-06-02 07:25:51
【问题描述】:

向我的网站添加指令时出现以下错误:

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

仅当我在我的站点中包含欢迎指令 (welcome.js) 时才会出现该错误。如果删除了导入,则控制器可以工作。

我的 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>"
    };
  });

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

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

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

    使用

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

    【讨论】:

    • 在控制器和指令定义中。
    • 谢谢,成功了!当我没有依赖项时,我总是省略括号吗?
    • @fwind,您只需要在整个应用程序中定义一次 Module 即可,无论您在模块级别上有什么依赖关系。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 2016-09-01
      • 2016-08-06
      相关资源
      最近更新 更多