Cameron
Cameron

Reputation: 28783

AngularJS ui-router to a state but use different URL

In my AngularJS application I want to catch errors and send the user to a 404 state like so:

$rootScope.$on('$stateNotFound',  function(event, unfoundState, fromState, fromParams){ 
    //console.log(unfoundState.to);
    //console.log(unfoundState.toParams);
    //console.log(unfoundState.options);
    $state.go('404');
});

This is for when a user clicks a bad link (e.g. has no state, as ones with states but no content are handled by the otherwise method) in the app, etc.

The code loads the 404 state fine:

.state('404',
        {
            views: {
                'body': {
                    templateUrl: 'partials/404.html',
                }
            }
        });

But what I want to do is change the URL to the state they tried to access, so basically load the 404 state but use the incorrect URL (as a 404 would work in a server environment).

I've looked into doing:

history.replaceState(null, null, unfoundState.to);
$state.go('404');

But that causes major errors in the app and changes the URL but not the state!

How can I do this?

Upvotes: 2

Views: 307

Answers (2)

JoseM
JoseM

Reputation: 4302

According to the docs, I think you can do:

$state.go('404',{},{location:false});

Note: I'm in the process of creating a plunkr to verify but I don't have time to finish it up completely right now

Upvotes: 1

Jscti
Jscti

Reputation: 14440

Try this to catch all URLs not matching any of your previous routes :

.state("404", {
    url: "*path", // will catch all URLs
    templateUrl: 'partials/404.html'
})

Upvotes: 1

Related Questions