Search code examples
angularjsroutesrequirejsroute-provider

Distributed route definition in AngularJS


I generally know that route definitions in AngularJS happen as follows:

var app = angular.module('app', []);
app.config(function ($routeProvider) {
$routeProvider.when("/", { templateUrl: "/partials/home.html" }).
               when("/profile", { templateUrl: "/partials/profile.html" }).
               when("/contact", { templateUrl: "/partials/contact.html" }).
               otherwise({ redirectTo: '/' });
});

What annoys me is that I want to modularize my application using RequireJS and I want to register routes where they are needed. For example, if I have a profile module I want to register my route from there. Same applies for the contact module. This centralization drives me crazy. Am I missing a point here or is there any good solution for my problem?


Solution

  • You can simply distribute the route configuration over your modules. The only thing you must do, register all modules in your "app"-module.

    angular.module('app', ['app.profile', 'app.contact'])
      .config(function ($routeProvider) {
        $routeProvider.when("/", { templateUrl: "/partials/home.html" })
                      .otherwise({ redirectTo: '/' });
      });
    
    angular.module('app.profile', [])
      .config(function ($routeProvider) {
        $routeProvider.when("/profile", { templateUrl: "/partials/profile.html" });
      });
    
    angular.module('app.contact', [])
      .config(function ($routeProvider) {
        $routeProvider.when("/contact", { templateUrl: "/partials/contact.html" });
      });