2

I get the following error when adding a directive to my site:

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

The error only occurs when I include the welcome-directive (welcome.js) in my site. If the import is removed the controller works.

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

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

2 Answers 2

6

You are redefining the module. Define module only once.

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')

Use

angular.module('my-app')  //Notice remove []
  .directive("welcome", function() {
  });
Sign up to request clarification or add additional context in comments.

3 Comments

in both the controller and the directive definitions.
Thanks, that did it! Do I always leave out the brackets when I have no dependencies?
@fwind, You need to define Module only once in entire application with whatever dependencies you have on module level.
3

passing a 2nd argument like this angular.module('my-app', []) creates a new module, use it only once.

To retrive a module use var module = angular.module('my-app') and use module.controller(... or module.directive(.... etc.,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.