Question

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?

Was it helpful?

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" });
  });

OTHER TIPS

You don't have to do the config of the $routeProvider all in one place. Go adding route definitions as need arises i.e. when you know you'll be using for example the profile module, you can then add the .when() clause that corresponds to its route.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top