Using Angular Module in a Javascript file

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In the last tutorial, our AngularJS script code is at the bottom of the page.  While it works, for larger applications we should use Angular modules in a separate Javascript file on its own.

This tutorial continues directly from the last tutorial.  So if you have not been there, go there first.

We replaced our script block of code with a reference to a Javascript file called app.js in a js subfolder…

script block replaced by script tag

script block replaced by script tag

If you prefer to move this script tag to the head instead of the bottom of the page, that’s fine.   Just make sure it is after the AngularJS library reference.

Our app.js contains the code …

wrapped in a closure

wrapped in a closure

It is the same code as before, except we wrapped everything up in a Javascript IIFE (Immediately Invoked Function Expression).  You can also say that it is wrapped in a Javascript closure.

And we then add  “use strict”…

use strict

use strict

Everything works just like before.  Unlike jQuery, we don’t need to wrap our angular code within a DOM ready function.  AngularJS takes care of that.

However, if you minify this JS file, it will break.  Learn why and how to fix this in the next tutorial.