Harry Harry - 1 year ago 43
AngularJS Question

Angularjs routing in different files

I'm checking out angular routing.


The examples I see have all the routes be defined in the same file. How do I have various routes be defined in different files / modules?

Answer Source

In AngularJS routes are defined in configuration block. Each AngularJS module can have multiple configuration blocks and you can define routes in each and every configuration block. The final routing for the entire application is a sum of routes defined in all modules.

In practice you can do it like:

angular.module('myModule1', []).config(function($routeProvider){
  //define module-specific routes here

angular.module('myModule2', []).config(function($routeProvider){
  //define module-specific routes here

angular.module('myApp', ['myModule1', 'myModule2']).config(function($routeProvider){
  //define app-level routes here

Regarding the split over files - I guess this largely depends on how you split AngularJS modules in files. What I would recommend is sticking to one-file equals one-module principle.

You can see all this applied to a larger-scale web application in angular-app, an effort to build a reference for a non-trivial application written in AngularJS:

In the mentioned app you can see routes defined in multiple files, ex.: