Including controller when routing in AngularJS

177 Views Asked by At

I'm building a fairly large single page web app with AngularJS and I'm trying to find the best way to make it very modular.

I'm using ngRoute to build my routes, my app.js contains:

...
app.config(function($routeProvider, $locationProvider) {
$routeProvider
    .when('/stats', {
        templateUrl : 'views/stats.html',
        controller  : 'StatController'
    })
    ...

In order for this to work I need to include my StatController on my main index.html file as well as including app.js.

<script src="/js/StatController.js"></script>

Seems reasonable when I include just 1 or 2 controller, but what if I have 30 controllers? do I still have to include them all in my index.html page or is there a way for Angular to include it only when it's needed (i.e., when requesting a new controller)

1

There are 1 best solutions below

0
On

Each view has attached a controller if you need some logic on the current view. The best practice is to separate features of your app in small pieces of routing file.For example you have to create a account section.You can create a accountRoute.js where you have you're module, like so :

angular.module('myModule').config(function ($stateProvider){
.state('someName',{/*add controllers templates here*/})
})

and other states maybe. If you need to create another future, for example dashboard, you can create another routing file, dashboardRoute.js, where you use the same angular module.This is a good practice to structure you're code to be more clean. So in dashboardRoute.js you will have:

angular.module('myModule').config(function ($stateProvider){
    .state('anotherStateName',{/*add controllers templates here for dashboard feature*/})
    })

All routes will be injected in the same module, so you will have access to them. Last but not least, you should have also a app.js file where you inject all you're module dependency needed, login routing and so on. In my opinion a controllers.js file is hard to debug, maintain and read. Each controller should be separated in a different .js file and added on index.html. I hope it helped.