17

I want to show 404 error page, but also I want to save wrong url in location.

If I'll do something like that:

$urlRouterProvider.otherwise('404');
$stateProvider
    .state('404', {
        url: '/404',
        template: error404Template
    });

url will change to /404. How I can show error message on wrong urls without changing actual url?

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
maxcold
  • 171
  • 1
  • 1
  • 5

2 Answers2

39

There is solution for this scenario. We'd use 1) one ui-router native feature and 2) one configuration setting. A working example could be observed here.

1) A native feature of ui-router state definitions is:

The url is not needed. State could be defined without its representation in location.

2) A configuration setting is:

path String | Function The url path you want to redirect to or a function rule that returns the url path. The function version is passed two params: $injector and $location

Solution: combination of these two. We would have state without url and custom otherwise:

$stateProvider
  .state('404', {
    // no url defined
    template: '<div>error</div>',
  })

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

Check that all in this working example

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
15

As of ui-router#0.2.15 you can use $state.go() and send option not to update the location:

$urlRouterProvider.otherwise(function($injector) {

  var $state = $injector.get('$state');

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

});
ilovett
  • 3,240
  • 33
  • 39
  • Thanks! This is perfectly working with both 'otherwise' and '$stateChangeError' interception for dynamic urls. – extempl Oct 04 '15 at 10:22