shyam
shyam

Reputation: 1388

UI Router conflicting when using similar URL pattern

I have the following 2 states defined in my app.config:

state('product-details', {
    url: '/products/:productId',
    templateUrl: '/pages/product-details/product-details.tmpl.html',
    controller: 'ProductDetailsController'
})

and

state('product-register', {
    url: '/products/register',
    templateUrl: '/pages/product-register/product-register.tmpl.html',
    controller: 'ProductRegisterController'
})

The problem I am facing is since both their URL patterns are similar, when I try to navigate to product-register state, the 'register' is interpreted by angularui-router as a productId and redirects me to product-details state instead.

After going through some similar questions on SO, I thought I would filter these URLs using regexes as explained here. But when I tried this, although the regex was matching properly in isolation, the state refused to change.

Then again after doing a bit of research I decided to merge the two states like this:

state('product-details', {
     url: '/products/:param',
    templateUrl: ['$stateParams', function($stateParams) {
        if($stateParams.param === 'register') {
            return '/pages/product-register/product-register.tmpl.html';
        } else {
            return '/pages/product-details/product-details.tmpl.html';
        }
    }],
    controller: ['$stateParams', function($stateParams) {
        if($stateParams.param === 'register') {
            return 'ProductRegisterController';
        } else {
            return 'ProductDetailsController';
        }
    }]
})

This also does not seem to work as expected. What am I missing? Isn't this a very normal thing you would have to do?

Upvotes: 3

Views: 529

Answers (2)

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

Try to move 'product-register' state before 'product-details' state.

Actually you need to differentiate your state URL pattern or else angular will fire the first match it will find.

Upvotes: 3

David Spence
David Spence

Reputation: 8079

You should be able to specify types for your parameters to match only certain states.

In your case you could use:

url: '/products/{productId:int}'

There are lots of other examples on the ui router page: https://github.com/angular-ui/ui-router/wiki/URL-Routing

Upvotes: 1

Related Questions