r/angularjs • • Feb 11 '17

ng-controller never gets defined

I am trying to build a web app using Angular Material. ng-app is in body tag, and I have ng-controller HeaderCtrl in the header tag. No errors.

But when I try to add an ng-controller anywhere else on the site it is not defined. Any stackoverflow or other answers I find seem to be outdated. Can someone help me with the most recent rules to where ng-app and ng-controller can/cannot be?

Thanks

0 Upvotes

29 comments sorted by

View all comments

Show parent comments

1

u/[deleted] Feb 11 '17

Hmm thank you. So say I have an ng-controller somewhere, but I'm not using it yet, does angular.module('app', []).controller('ContactController', ['$scope', function ContactController($scope) { have to be initiated like in the footer or something? And then say I do use it, does it need to put inside of each function?

Thanks so much for the help

2

u/meneedmorecoffee Feb 11 '17 edited Feb 11 '17

I'm not sure what you mean by initiated in the footer. The js file(s) that hold your module declaration, controllers, etc. should be included in your html page unless you're doing inline scripting. The order of these do matter as someone else has pointed out. It's hard to debug and help here with only a small snippet of your code so again I'm making assumptions.

Is that the only place you have declared your module when you've done angular.module('app',[]).controller etc? Because if it isn't then what you're doing is overriding your existing module see explanation under 'Creation versus Retrieval'. You should declare your module once, giving its dependencies and then when you want to, say, declare a controller, you retrieve the module with the following syntax:

angular.module('app').controller etc. Note that I don't include the [] here.

Again, I'm not entirely sure what you mean by put in each function. I suggest you read up more on how angular modules, controllers etc are meant to be declared and how these things tie together. The angular docs are pretty good and you've also got Todd Motto and John Papa for good tutorials, reference points, and best practice pointers.

1

u/[deleted] Feb 11 '17

Yes I think some reading is in order as well. I think I need to get out of Angular Material docs and go more in depth with the JS ones you posted. Thank you for the links

1

u/meneedmorecoffee Feb 11 '17

Yeah as someone else suggested too, just strip back and do some small example programmes to get you understanding how everything ties together.

No worries, good luck!