fwind
fwind

Reputation: 1314

Angular: Controller is undefined when adding a directive

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

Upvotes: 2

Views: 626

Answers (2)

tekkavi
tekkavi

Reputation: 894

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.,

Upvotes: 3

Satpal
Satpal

Reputation: 133403

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() {
  });

Upvotes: 6

Related Questions