Angular UI Router - allow ANY query string parameter

I use Angular UI Router and it works well in most situations. However, I have a situation where I do not know in advance the names of the query string parameters.

Typically, with a UI router, you define a route something like this:

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

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

However, with the UI router, you cannot access query string parameters not specified in the route definition.

The router that comes with the Angular framework allows you to do this. So I tried using the location service with my UI router setup. It does the job.

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

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

When I want to get the values โ€‹โ€‹of a query string, I just use:

 $location.search() 

This updates the URL but does not repeat the creation of the controller (for example, $ state.go ($ state.current, {}, {reload: true})). This does not seem to be a big problem, because I can simply reload the data myself. However, if you use the back button in the browser, it changes the URL again, but does not create a duplicate copy of the controller.

Anyway

  • Can I get this to work using only a UI router?

  • Get a workaround for using $ location to actually recreate the controller instance.

As a last resort, I also tried setting up a window.location update, but this updates the whole page, which is not acceptable.

thanks

+6
source share
1 answer

You can pass non-url parameters that are not displayed in the 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 display in the URL

You can access this parameter in your controller using $stateParams

 $stateParams.optParam 

Here is a useful blog

0
source

Source: https://habr.com/ru/post/982309/


All Articles