Skip to content

State provider routes

Jens Melgaard edited this page Jul 29, 2013 · 5 revisions

As covered under the Route Provider - Basic Configuration section, states can be activated by routes.

But instead of having to configure routes for each state, a route can be defined directly through the state provider.

This is done by setting the route property on a state, and optionally a reloadOnSearch.

angular.module('phonecat', ['dotjem.routing']).
  config(['$stateProvider', function($stateProvider) {
  $stateProvider
      .state('phones', { route: '/phones' })
      .state('tablets', { route: '/tablets' });
}]);

The same features for defining the route with parameters exists here, so /phones, /phones/:id, /phones/{id}, /phones/{num:id}, /phones/{regex(^ph-\\d+$)} are all valid ways, as this is just a shorthand for calling $routeProvider.when(<route as defined on state>, { state: <state name> }).

Routes in Child States

angular.module('phonecat', ['dotjem.routing']).
  config(['$stateProvider', function($stateProvider) {
  $stateProvider
      .state('phones', { route: '/phones' })
      .state('phones.category', { route: '/:category' })
      .state('phones.detail', { route: '/:id', reloadOnSearch: false })
}]);

The above will be the same as configuring the $routeProvider as in the following example:

angular.module('phonecat', ['dotjem.routing']).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider
      .when('/phones', { state: 'phones' })
      .when('/phones/:category', { state: 'phones.category' })
      .when('/phones/:id', { state: 'phones.detail', reloadOnSearch: false })
}]);

As you may notice, the defined route on child states are concatenated to the parent state. What happens is that the state provider will concatenate all defined routes until the root state to define the full route.

If you wish to have a child state activated by a route that doesn't have any relation to any of the routes defined on any of the above states, you need to use the $routeProvider directly instead:

angular.module('phonecat', ['dotjem.routing']).
  config(['$stateProvider', '$routeProvider', function($stateProvider, $routeProvider) {
  $stateProvider
      .state('phones', { route: '/phones' })
      .state('phones.category', { route: '/:category' })
      .state('phones.detail', { ... });

  $routeProvider.
      .when('/{regex(^nokia.*|iphone.*|htc.*$):id}', { state: 'phones.detail' });
}]);

The reason for this is that the other case seems to be the more common case.

Clone this wiki locally