David Michael Gang David Michael Gang - 9 months ago 53
AngularJS Question

how to pass the query parameter with the othwerwise function

Given the following javascript:

.state('search', {
url: '/search?query',


When I access the page


I get redirected to


but the query parameter gets lost.

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


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