Stud Sterkel
Stud Sterkel

Reputation: 1163

Avoiding dynamic routes with ui-router

I am using express, angular, and ui-router for my webpage. I would like the url for each user's page to be very simple: www.mysite.com/username

This is similar to Twitter's design. My angular state provider for the user pages looks like this:

$stateProvider
   .state('userPage', {
        url: '/:username',
        templateUrl: 'js/user-page/user-page.html',
        controller: 'UserPageCtrl'
});

The only issue is now when I try to navigate to any other page whose state is defined with only one URL part (ie. www.mysite.com/login), the app always parses the URL as a user page (but without being able to find a user).

Is there any way to tell angular to try and load the URL as a defined state before treating the url as a dynamic parameter?

I can simply require all other routes to have two parameters (ie. www.mysite.com/login/userlogin), but that doesn't seem very elegant.

Upvotes: 0

Views: 263

Answers (1)

tommyd456
tommyd456

Reputation: 10683

You just need to define the login state first. Order is important.

$stateProvider
   .state('login', {
        url: '/login',
        templateUrl: 'somewhere/login.html',
        controller: 'LoginPageCtrl'
    },
   .state('userPage', {
        url: '/:username',
        templateUrl: 'js/user-page/user-page.html',
        controller: 'UserPageCtrl'
    },

});

If a user navigates to /login then a matching state will be searched for. It will check your first state, then the second and so on until a matching state is found. In this case, the login state will match so the searching for another matching state will cease.

Upvotes: 1

Related Questions