0
votes

This should be simple but I just can't figure it out.

I have two routes:

$stateProvider

    .state('users', {
        url: '/users',
        views: {'@': {
            templateUrl: 'templates/users.tpl.html',
            controller: 'UsersCtrl as users'
        }}
    })
    .state('users.edit', {
        url: '/{userId}',
        views: {'@': {
            templateUrl: 'templates/editUser.tpl.html',
            controller: 'EditUserCtrl as editUser'
        }}
    });

This works fine if you use a ui-sref or $state.go to navigate to the "users" state by name, but if you type domain.com/users/ into the URL bar it goes to the edit state with empty userId parameter even though there is nothing after the trailing stash.

Normally this wouldn't be a problem but firing the editUser route with no userId causes console errors which would be a pain to fix.

Is this easily fixable?

2
Try changing either the first url to /users/ (add a trailing slash) or change the second url to /users/{userId}. I suspect that one of these is confusing the other based on the /users/ part of the URL path. - Dr. Cool
The first one stops /users working without a slash and causes a double slash when going to the second route and the second one makes the url /users/users. Just to be clear, I need it to go to the parent route if the URL is "/users" or "/users/" but if it's "/users/something" then it needs to go to the edit page. - jonhobbs

2 Answers

0
votes

Your states definition should be

$stateProvider

.state('users', {
    url: '/users',
    views: {'@': {
        templateUrl: 'templates/users.tpl.html',
        controller: 'UsersCtrl as users'
    }}
})
.state('users.edit', {
    url: '/edit/{userId}',
    views: {'@': {
        templateUrl: 'templates/editUser.tpl.html',
        controller: 'EditUserCtrl as editUser'
    }}
});

your child state url should be '/edit/{userId}'. When we create a child state its url automatically added its parent state url. So if your url is '/{userId}' it will be 'domain.com/users/{userId}'. That's why for domain.com/users/ its navigate to the state users.edit with null parameter value.

https://github.com/angular-ui/ui-router/wiki/nested-states-%26-nested-views