celsomtrindade
celsomtrindade

Reputation: 4671

AngularJs ui-router access direct trought url param

Currently I'm building a webApp and I'd like to create a link to have direct access to a specific user, city or company. For example:

I can set the proper name, id, or whatever the param is. But the problem is when I try to access this state or other page, they have conflict. For example, if I try to go to the homepage, which has this configuration:

.state('home', {
    url: '/Welcome',
    //..other configs
})

The router try to get the url as a param and send the user to the page of the company, user or city.

Is there a way to achieve this result?


Edit:

Currently, to avoid this conflict, I'm using my routing like this:

.state('city', {
    url: '/City/:cityName',
    //..other configs
})

But I'd like, if possible, to use like this:

.state('city', {
    url: '/:cityName',
    //..other configs
})

Because I want users to be able to access the page by typing the name direct on the url.

Upvotes: 0

Views: 154

Answers (1)

Martijn Welker
Martijn Welker

Reputation: 5605

If I understand you correctly you probably want something like this.

.state('home', {
    url: '/welcome',
    //..other configs 
})
.state('cities', {
    url: '/cities/:parameter'
})

This way you remove the conflict.


Update: You could also make an array with excluded parameters, if the parameter is not in the excluded list, redirect to a different state.

.state('home', {
    url: '/:slug',
    //..other configs 
})
.state('cities', {
    url: '/cities/:slug'
})

var excludedWords = ['welcome', 'homepage'];
$rootScope.on('$stateChangeStart', function(event) {
    if(excludedWords.indexOf($stateParams.slug) !== -1) {
        event.preventDefault();
        $state.go('cities', $stateParams);
    } 
});

This way, if a user enters /welcome, he/she won't get redirected to the /cities/welcome page, but if he/she enters /newyork he/she will be redirected to /cities/newyork

Upvotes: 1

Related Questions