1

I need to check if my current URL match or not with an state URL (using ui-router). The issue here is that I am loading dynamically all my states, so when the user refresh a page this URL is not loaded yet so I am being redirected to the otherwise URL.

I am planning to load all my states in the otherwise function and check the one that math with my current URL and load it right away, so maybe in this way I won't be redirected to my default URL.

Example:
My current URL: asd/5/it-is-a-slug
My state URL: /asd/:id/:slug

Any ideas?

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
ermamud
  • 113
  • 1
  • 2
  • 7

1 Answers1

1

The way to go here, I'd say, is to use UI-Router built in $urlRouterProvider.deferIntercept(defer) for that. Check some other:

The point is the

$urlRouterProvider.deferIntercept(defer)

Disables (or enables) deferring location change interception.

If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler.

There is a working example

in a config() phase we will defer execution:

app.config(function ($locationProvider, $urlRouterProvider, $stateProvider) {
  
    $urlRouterProvider.deferIntercept();
    ...

In a .run() phase we will load dynamic stuff:

$http
  .get("myJson.json")
  .success(function(data)
  {
    angular.forEach(data, function (value, key) 
    { 
      var state = {
        "url": value.url,
        "parent" : value.parent,
        "abstract": value.abstract,
        "views": {}
      };
      
      angular.forEach(value.views, function (view) 
      {
        state.views[view.name] = {
          templateUrl : view.templateUrl,
        };
      });

      $stateProviderRef.state(value.name, state);
    });
    // Configures $urlRouter's listener *after* your custom listener
    
    $urlRouter.sync();
    $urlRouter.listen();
  });

Example in action

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Agree with Radim, deferIntercept is the thing to use. For the other half of the question (how to get a state based on a url), see this answer: http://stackoverflow.com/questions/29892353/angular-ui-router-resolve-state-from-url/30926025#30926025 – Chris T Jun 30 '15 at 14:58