4

In a very basic Angular app we have

<head>...
<script src="app.js"></script>
<script src="maincontroller.js"></script>

App defines the app module, and controller then hangs off app as app.controller("MainController..") If the order of the two scripts is reversed, the app will throw an error "app is not defined".

Is there a way around this load order dependency? My fear is that as it becomes more complex, I will get script order dependencies. And perhaps I might want to load my scripts async as well.

Thank you.

1

2 Answers 2

3

See, for example, this plunker: http://plnkr.co/edit/kqVqTHxl4tc6mIV5bDbQ

I've defined SomeService in an own file, svc.js. I've defined the module and the main controller in app.js. And even though the MainController depends on that service that "loads later", the dependency is figured out, and injected. All you should worry about is: put the module definition first.


Also: Don't store the application inside a global variable called app, instead, use angular.module with the name of the module to retrieve a reference to it:

angular.module('SomeModuleName').controller(...)

Any kind of global variables are generally not a good practice.

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

Comments

2

Look at using Angular and Browserify or Angular and RequireJS. Browserify and RequireJS are module loaders that let you keep 1 script reference in your index.html.

Browserify is based on a build step that will bundle all your JS into 1 file.

RequireJS is an Asynchronous Module Definition (AMD) loader, that can load your files asynchronously.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.