Cameron
Cameron

Reputation: 28783

AngularJS ui-router otherwise to state instead of url?

I am using AngularJS and ui-router and in my app.js. I have the following line:

$urlRouterProvider.otherwise('/');

However I do not want it to send the user to a URL but instead to a state:

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

Normally I would just do this:

$state.go('404');

How can I do this for the otherwise method?

Note: that my 404 state does not have a URL, so basically it keeps the URL that the user has entered or visited and just changes the template.

Upvotes: 11

Views: 4949

Answers (3)

danijelf
danijelf

Reputation: 110

Try This.

$urlRouterProvider.otherwise(function($injector, $location){
    $injector.get('$state').go('404');
});

Upvotes: 3

tucq88
tucq88

Reputation: 418

Just a small improvement to @kdlcruz's answer:

$urlRouterProvider.otherwise(function($injector){
    $injector.invoke(['$state', function($state) {
        $state.go('404', {}, { location: false } );
    }]);
});

By doing that, you still able to keep the incorrect the URL and only state is changed.

Upvotes: 2

kdlcruz
kdlcruz

Reputation: 1388

I think you achieved that with this code

$urlRouterProvider.otherwise(function($injector, $location){
  $injector.invoke(['$state', function($state) {
    $state.go('404');
  }]);
}); 

Upvotes: 23

Related Questions