最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to pass the query parameter with the othwerwise function - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share edited May 3, 2015 at 5:08 Radim Köhler 124k48 gold badges242 silver badges340 bronze badges asked Apr 29, 2015 at 14:49 David Michael GangDavid Michael Gang 7,30910 gold badges55 silver badges105 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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

You don't need to grab injector and $state.go, not at all. The argument to otherwise method can be a URL path, which can contain parameters in it.

So in your particular case, following code can lead you to base_url/search?query=x

$urlRouterProvider.otherwise("/search?query=x");

Alternatively, the argument can be a function that returns a URL path. If you are not sure what URL parameters it could have, you just need to get the parameters from $location then format to the URL-like string and return it.

$urlRouterProvider.otherwise(function($injector, $location) {
    var params = $location.search()

    // format params to 'p1=v1&p2=v2' style
    var formatted = Object.keys(params).map(function(key) {
        return key + '=' + params[key]
    }).join('&')

    return '/search?' + formatted
});
发布评论

评论列表(0)

  1. 暂无评论