How to find a reason AngularJS "Argument 'MyCtrl' is not a function, got undefined"
When AngularJS crashes with an error "Argument 'MyCtrl' is not a function, got undefined" it's may be little bit challenging to find a reason why.
Here I want to make a kind of a "check list", what should you check when got an error
- Is file with 'MyCtrl' connected via html? (check twice if you concat or uglify your files)
<script src='path/to/controllers.js'></script>
- Is 'MyCtrl' defined correctly?
There are a few patterns:
app.controller('MyCtrl', ['$scope', function ($scope) {...}])
app.controller('MyCtrl', function ($scope) {...})
var MyCtrl = function ($scope) {...})
- Is 'MyCtrl' defined in right module?
- Is "MyCtrl's" module added to app dependencies?
angular.module('app', ['app.sources']);
-
If you define your module multiple times, you should define it in this order:
- First define should be like
angular.module('app.sources', []);
(with [ ]
)
- Subsequent defines should be like
angular.module('app.sources');
(without [ ]
)
Important: Declaration order is important - definition with [ ]
should go first.
- Check that module is defined only once. You may have forgotten to rename module after copy-paste. Check src for string like
angular.module('app.sources', []);
Check your
'ng-app'
. Better to use only one of these with name likeng-app='app'
(In other words do not define multiple unnamed ngApp directives)Is your controller's syntax correct for your AngularJS version?
(There is a difference between definition in Angular 1.0.x and 1.2.x and higher. With Angular versions greater than 1.3.x, you cannot declare a global constructor function and use it with ng-controller)
If you're using the ng-controller
with "controller as" syntax, be sure to check that the name of the controller is correct.
My case:
//controller register
angular.module("myApp").controller("someController", SomeController)
//in my code
<div ng-controller="SomeController as vm"></div>
Notice that I used ng-controller="SomeController as vm"
, where SomeController
has a capital S
.
It should have been with a lowercase s
because that's how I registered it.
So, check that your controller name is correct.