How can I preserve $location.search()
with
$routeProvider.otherwise({redirectTo: xxx})
I know, I can use a function there, which gets the old object $location.search()
as the third argument. I mostly care about a single key, let's call it a
, and I tried
function(a, b, search) {
return "/mainpage?a=" + search[a];
}
but it always ends with /mainpage?a=undefined
. What's worse, it crashes my debugger, which slows me down. Moreover, this doesn't work for all keys (which I may need later).
I have made a new approach, where you listen for
$routeChangeStart
and modify thesearch()
if the previous (non-existing) page contained important GET parameters. Complete source and a demo can be found on this Plunker.The concept is similar to @Mikko's solution, but the implementation is a bit different (no custom provider) and it works as per author's instructions.
The essence
The
run
function sets a listener for$routeChangeStart
and also remembers previous values of thesearch()
value (the GET params).When the app is redirected to the default route, it checks for the previous value of the
search()
parameters and extracts only the important ones. If any, it overrides thesearch()
value and therefore sets the important GET parameters to the default route.I have made an
URL
constant in which one can set the default route and specify the important parameters. The code is the following:The demo
The first link contains 3 parameters on a non-existing URL. The page is correctly redirected to the default route and only the 2 important ones are preserved.
The second and fourth links doesn't contain any parameters and both links don't apply any additional parameters (regardless on which page you are when you click them).
The third link also contains 3 parameters on the default route and all of them are preserved (no redirecting takes place).