cortharlow cortharlow - 6 months ago 9x
Javascript Question

Modularizing Angular

I am starting a new Angular project and trying to modularize all of my code – I'm tired of having massive app.js files and, because I'm developing a platform for a company, it's important my code is neat and modularized for easy testing, cleanliness, and ease of transition to Angular 2.

Currently, I have three angular files setting everything up:


.module('app', [
/* Shared Modules */
/* Feature Areas */


.module('app', [
/* Angular Modules */
/* 3rd-party Modules */


function($stateProvider, $urlRouterProvider, $locationProvider){

// Unknown URLs go to 404
// No route goes to index
$urlRouterProvider.when('', '/');

// State provider for routing
.state('home', {
url: '/',
views: {
'': {
templateUrl: 'home/_home.html'

This is my index.html

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" href="/content/stylesheets/screen.css">

<!-- Angular Dependencies -->
<script type="text/javascript" src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src=""></script>

<!-- Angular Modules -->
<script src="/app/app.config.js"></script>
<script src="/app/app.states.js"></script>
<script src="/app/app.module.js"></script>
<body ng-app="app">
<div id="wrapper">
<div ui-view></div>

I keep hitting this error:

Uncaught Error: [$injector:modulerr]

What am I doing wrong? I'm having a hard time understanding how I get my various Angular files to interact with each other. I left out a controller of my state because I'm just testing the view right now.


By writing :

angular.module('app', [
    /* Shared Modules */
    /* Feature Areas */

You create a module named app which requires 2 modules : app.config and app.states. If one of these is missing or not valid, the app module can't start.

In your config.js, you write angular.module('app', [...]). This will create a module named app with dependencies between the '[...]'. However, you've already created a module named 'app' in your module.js.

Change the module name, in config.js to angular.module('app.config', [...]).

In your states.js file, there is another thing: angular.module('app') gives you the module you've created in your module.js file. You can call the config method on it, this is not a problem. However, you define, in your app module a dependecy to app.states. You can remove this dependency, or replace angular.module('app') by angular.module('app.states', []).config(...)

Hope it helps you.