Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>"
    };
  });
like image 699
fwind Avatar asked Jan 18 '26 06:01

fwind


1 Answers

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() {
  });
like image 95
Satpal Avatar answered Jan 19 '26 19:01

Satpal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!