0

Please can anyone explain why the following throws an "Argument 'MainCtrl' is not a function, got undefined" error which seems to be tied into the use of module dependency injection with directives(?!).

angular.module('app', [])
  .controller('MainCtrl', [function() {
    var self = this;
    self.name = "will this work";
    self.items = [
      {
        name: "name 1",
        test: "test 1"
      },
      {
        name: "name 2",
        test: "test 2"
      }
    ];
  }]);

angular.module('app',[])
  .directive('typeahead', [function() {
    return {
      templateUrl: 'type-ahead.html',
      restrict: 'AEC',
      scope: {
        items: '=',
        prompt: '@',
        title: '@',
        subtitle: '@',
        model: '=',
        onSelect: '&'
      }, <...more code>

Yet it will work perfectly fine when I remove the

[ ]

module dependency braces from the directive to read

angular.module('app').directive('typeahead', ...)

It also works perfectly fine if I define the directive as a cascade following the controller definition i.e.

angular.module('app', [])
      .controller('MainCtrl', [function() {
        var self = this;
        self.name = "will this work";
        self.items = [
          {
            name: "name 1",
            test: "test 1"
          },
          {
            name: "name 2",
            test: "test 2"
          }
        ];
      }])

    .directive('typeahead', [function() {
        return {

Thanks in advance!

2
  • 1
    angular.module('app', []) creates a module, angular.module('app') gets already created module. When you create a module again, yes obviously it is created again and anything registered before is gone for good. Commented Feb 1, 2015 at 2:00
  • Thanks - makes perfect sense now Commented Feb 1, 2015 at 2:16

1 Answer 1

2

You are running into Angular's Creation versus Retrieval Problem:

Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.

The first time you run angular.module('app',[]), Angular will create a module called app. Next time, you only need to run angular.module('app'), Angular will try to load the existing module app.

Since you call angular.module('app',[]) once again, module app has been re-initialized. That's why MainCtrl is undefined now.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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