Search code examples
javascriptangularjsangular-ui-routerangular-ui

how to pass the query parameter with the othwerwise function


Given the following javascript:

$stateProvider
  .state('search', {
    url: '/search?query',
})   
;

$urlRouterProvider.otherwise("search");

When I access the page

base_url?query=x

I get redirected to

base_url/search

but the query parameter gets lost.

Is there a way to pass the query parameter with the otherwise function?


Solution

  • There is a working plunker

    The UI-Router has native solution here.

    The otherwise does not have to be the "url" string, it could be a function.

    Check it in action in this Q & A:

    How not to change url when show 404 error page with ui-router

    The code could be like this:

    $urlRouterProvider.otherwise(function($injector, $location){
        var state = $injector.get('$state');
        state.go("search", $location.search()); // here we get { query: ... }
        return $location.path();
    });
    

    The $location.search() will give us params object, which could be like: { query: ... }. We take it and redirect to state search with this params...

    Check it here