0
votes

I have declared angular module in app.js like

var mainModule = angular.module('mainModule ', ["subModule"]);
var subModule = angular.module('subModule ', []);

and a JS file subController.js, that have controller defined like

subModule .controller("subController", ['$scope', '$timeout',"$rootScope", function ($scope, $timeout, $rootScope) {
...
}]);

and a HTML file subTemplate.html like

//custom directive that will load the js file with ajax call
<loadscript src="js/controllers/subController.js"></loadscript>
<div data-ng-controller="subController">
...
</div>

above code giving me error like: Error: [ng:areq] Argument 'subController' is not a function, got undefined

if I changed the controller declaration in subController.js file like below then it is working(but I dont want to declare the controller like this)

function subController($scope, $timeout, $rootScope) {
...
};

I need to implement module wise controller declaration.

Can anybody help?

Thanks.

1
I'm guessing that in subController.js you'r missing : "var subModule = angular.module('subModule'); ". You have to get a reference to 'subModule' or you won't be able to add things to it. You could declare subModule in app.js as a global variable to make it available in all other files, but I don't recommend it. - Yair Tavor
Actually, I missed the comment about the directive doing lazy loading. As of now, angular does not support lazy loading. This means that once the app start running you can't add new controllers, services or other stuff to existing modules. There are ways around it though, check out ify.io/lazy-loading-in-angularjs . that's what I used in my project when I faced the same problem. - Yair Tavor
Thanks @YairTavor, Excellent article for understanding lazy loading in angular js. - Gaurav

1 Answers

0
votes

you are loading you js lazily which contains the definition of "subController", but the inline code ng-controller="subController" get executed even before the response comes back... and hence the error.

<loadscript src="js/controllers/subController.js"></loadscript>
<div data-ng-controller="subController">
...
</div>

i see no way around this error unless you write another directive for ng-controller which transcludes the inner element only after the js file have been loaded