Michal_Szulc Michal_Szulc - 3 months ago 12
AngularJS Question

Point [ui-router otherwise] to static page

I have

login.html
with different layout than other sites so I've put it in my app directory and I do not have state for it.
However I'd like to redirect to
www.example/login.html
if user get 404.

I tried to get it by configuring ui-router inside of one module:

function routeConfig($urlRouterProvider, $windowProvider) {
var $window = $windowProvider.$get();
$urlRouterProvider.otherwise(function($injector, $window){
$window.location.href = '/login.html';
});
}


But unfortunatelly I got


Error: $window.location is undefined


How can I redirect to this 'static page'?

Answer

Your otherwise is a callback function of which, is a closure itself so your var $window = $windowProvider.$get() is NOT the same as the argument $window in your callback function, and hence the undefined.

The correct code should be:

function routeConfig($urlRouterProvider, $windowProvider) {
    $urlRouterProvider.otherwise(function($injector){
        var $window = $windowProvider.$get(); // put this line of code inside
        $window.location.href = '/login.html';
    });
}