2
votes

The Angular UI-Router documentation uses the following example for redirecting:

$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
    if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
        $state.transitionTo(state, $match, false);
    }
}]);

https://github.com/angular-ui/ui-router/wiki/URL-Routing#when-for-redirection

My question is about state.url. You can get a state's url by using the $state service, e.g. $state.get('home')

But this is a service and is not available in the config phase, so how would I go about obtaining a states url to put it as the first parameter of $urlRouterProvider.when?

2

2 Answers

0
votes

$routeProvider is a shim the implements the current AngularJS $route / $routeProvider API on top of $stateProvider, to make it easier for people to transition applications to $stateProvider step by step -- it simply fudges the route definition into a state definition by making up a name, and some other small things.

$urlRouterProvider simply has the responsibility of watching $location, and when it changes running through a list of rules one by one until one matches. How exactly "matching" is defined and what happens when a rule matches is up to that rule; at the lowest level its just a function that returns true if it has handled the URL. However there is support built on top of this for rules that are RegExps, as well as path patterns with placeholders (as used by state.url) that are compiled into rules via $urlMatcherFactory. $urlRouterProvider also supports redirects.

As it stands $urlRouterProvider should already be faster than the corresponding code in $routeProvider, because it doesn't re-parse url patterns on every location change, but instead hangs on to the compiled UrlMatcher objects.

0
votes

This actually works nicer, because you don't have to create a regex:

var forks = {
  issueConditionFork: function() {
    if ($stateParams.serviceType === 'sell') {
      return 'condition';
    }
  }
};

$rootScope.$on('$stateChangeStart', function(event, state) {
  var fork;
  fork = forks[state.name];
  if (fork) {
    $state.go(fork());
    return event.preventDefault();
  }
});

In your run block.