Angular UI Router - allow ANY query string parameter

泪湿孤枕 提交于 2020-01-02 02:44:27

问题


I am using the Angular UI Router and this works well in most situations. However, I have a situation where I don't know the names of the query string parameters ahead of time.

So normally with UI router you would define a route something like this:

$stateProvider.state('test', {
	url: '/test?testQueryStringParam',
	templateUrl: 'Test.html',
	controller: 'TestController'
});

Then in my controller I can access the testQueryStringParam using $stateParams.

However, with UI router you can't access any query string parameters not specified in the route definition.

The router that comes with the Angular framework, does allow you to do this. So I have tried using the $location service with my UI router defintion. This does sort of work.

When I want to add a query string parameter I use:

$location.search("paramName", "paramValue");

When I want to get the query string values I just use:

$location.search()

This updates the URL, but doesn't re-instantiate the controller (like $state.go($state.current, {}, {reload: true}) would). This doesn't seem like a big problem because I can just re-load the data myself. However, if you use the back button in the browser, again it changes the URL, but doesn't re-instantiate the controller.

Is there anyway

  1. I can get this to work using just the UI Router?

  2. Get the workaround of using $location to actually re-instantiate the controller.?

As a last resort I also tried directing updating the window.location, but this refreshes the entire page which isn't acceptable.

Thanks


回答1:


You can pass non url parameters that do not appear in URL

$stateProvider.state('test', {
    url: '/test?testQueryStringParam',
    params: {
    optParam: null,
    },
    templateUrl: 'Test.html',
    controller: 'TestController'
});

As you can see, optParam is an optional parameter with a default value of null and will not be visible in the URL

You can access this param in your controller using $stateParams

$stateParams.optParam

Here is a helpful blog



来源:https://stackoverflow.com/questions/28449774/angular-ui-router-allow-any-query-string-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!