0

I am newbie to angular. Currently all of my controllers are defined in following controllers.js file on following patterns

function A($scope){.....}
function B($scope){.....}
function MainCtrl($http) {.....}
.
.
.
angular
    .module('myApp')
    .controller('A', A)
    .controller('B', B)
    .controller('MainCtrl', MainCtrl)

Things are working fine. But now, i want to create separate .js file for each controller. Have created a directory named controllers under root and added A.js and B.js there

A.js looks like following

var app = angular.module('myApp', []);
app.controller('A', ['$scope', function ($scope) {
.
.
.
}]);

controllers.js file is already been added to index.html

<script src="js/controllers.js"></script>
<script src="controllers/A.js"></script>

and now when i add A.js or B.js files in index.html it throws error saying MainCtrl isn't defined. But it's sure it's defined in controllers.js. I can see following link in console.

http://errors.angularjs.org/1.5.0/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined

Can anybody suggest some solution

2

1 Answer 1

1

You are using the wrong order in your html file. Your A controller is defined after your controllers which then means controllers doesn't know anything about it by the time it loads.

 <script src="controllers/A.js"></script>
 <script src="js/controllers.js"></script>

However I suggest you move towards using something like require.js for loading your dependencies. I know it might look strange to you but since you've begun learning, moving in the right path helps you a lot.

Here is a very simple introduction:

https://kielczewski.eu/2013/04/integrating-angularjs-with-requirejs/

And a bit of explanation:

Imagine if you have something which gives you whatever you depend on (lets say controllerA). We call it dependency resolver. Now you just need to tell it I want controllerA and it gives you that without need to do anything extra.

Of course you need to tell it where to find all of yours files in it's config but that's ALL.

Good luck

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.