My angularjs controller function is never called. I see all the js files included in my sources, it's just not ever hitting the initialization of my controller. What is wrong with this code?
eventListCtrl.js:
eventsApp.controller('eventListCtrl', ['$scope', function ($scope) {
// this code is never called
alert('controller initializing');
$scope.name = "Test";
}]);
app.js:
'use strict';
var eventsApp = angular.module('eventsApp', []);
Index.cshtml:
<div ng-controller="eventListCtrl">
<div class="row">
<div class="spann11">
<h2>{{name}}</h2>
</div>
</div>
</div>
<script src="/scripts/vendor/angular.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/controllers/eventListCtrl.js"></script>
asked Mar 24, 2014 at 15:18
Ryan Langton
6,18016 gold badges56 silver badges105 bronze badges
4 Answers 4
You need to do this
<html ng-app="eventsApp">
So you actually activate the module
answered Mar 24, 2014 at 15:48
iConnor
20.2k14 gold badges67 silver badges98 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Ryan Langton
Doh, not sure how I missed this!
I want to post my issue/resolution here in case anyone does the same thing as me.
<div ng-controller="coolCtrl" ng-if="VAR">
I was trying to init a controller on an element that didn't get created (because of the ng-if="var" )
facepalm
answered Jun 12, 2015 at 0:44
James Harrington
3,22032 silver badges32 bronze badges
1 Comment
mate.gvo
Thank you! I made the same mistake by adding ng-show on the controller wrapper :)
Wild guess:
angular.module('eventsApp').controller('eventListCtrl', ['$scope', function ($scope) {
// this code is never called
alert('controller initializing');
$scope.name = "Test";
}]);
in your controller file?
answered Mar 24, 2014 at 15:25
Joe Minichino
2,76524 silver badges20 bronze badges
6 Comments
trysis
This is exactly what I was thinking when I first saw the question. AngularJS is very trial-by-fire.
iConnor
This would make no difference, It's identical to what he's doing already
Joe Minichino
the API on
module is just very bad. Adding a second parameter makes it an initializer and people get confused.Joe Minichino
@Connor not true. unless he made
eventsApp global which would be very bad, in which case the answer still suggesting best practice.iConnor
@JoeMinichino it is global, as seen in the post :) and plus, in production it's likely to concatenate your files anyway, and it's not bad practice to have your namespace global
|
<html ng-app="eventsApp">
<div ng-controller="eventListCtrl">
<div class="row">
<div class="spann11">
<h2>{{name}}</h2>
</div>
</div>
</div>
<script src="/scripts/vendor/angular.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/controllers/eventListCtrl.js"></script>
</html>
This should fix it
Comments
lang-js
ng-app="eventsApp"anywhere? And did you recreateeventsAppwithin your controller?ng-appoutside the<div ng-controller="...">.