Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - 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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Is file with 'MyCtrl' connected via html? (check twice if you concat or uglify your files)
<script src='path/to/controllers.js'></script>
  1. Is 'MyCtrl' defined correctly?

There are a few patterns:

app.controller('MyCtrl', ['$scope', function ($scope) {...}])

app.controller('MyCtrl', function ($scope) {...})

var MyCtrl = function ($scope) {...})
  1. Is 'MyCtrl' defined in right module?
  2. Is "MyCtrl's" module added to app dependencies?
angular.module('app', ['app.sources']);
  1. 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.

  1. 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', []);
  1. Check your 'ng-app'. Better to use only one of these with name like ng-app='app' (In other words do not define multiple unnamed ngApp directives)

  2. 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...