Save url ui-router
I have a web application with an entry point to another application. This way, by the time the user gets to my application, they have some parameters in the url:
http://myapp.com/#/new?param1=value¶m2=value2
In my application, I have 3-4 tabs, each of which is its own state and is accessed with ui-sref="state"
The problem is that when I switch to any of these states, I lose the options that the user came with originally.
In a nutshell, I want http://myapp.com/#/differentstate?param1=value¶m2=value2
instead http://myapp.com/#/differentstate
when switching states.
I'm not sure how to install this ... Thanks!
source to share
inside your angular app function .run()
you can do this: (you will need DI $rootScope
and $location
)
var locationSearch;
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
//save location.search so we can add it back after transition is done
locationSearch = $location.search();
});
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
//restore all query string parameters back to $location.search
$location.search(locationSearch);
});
source to share
Setting $ location.search only works when you stay in the same window. To bind all links, you need to manually extend the ui-sref to include url parameters. Your links can now be "Open in New Tab" and save options. This code also includes a kludge to convert ~ 2F and% 2F to /, so your links stay the same. For this:
.run(function ($rootScope, $state, $location ) {
// Url parameters
var locationSearch = $location.search();
// Set param1
$rootScope.site = {};
$rootScope.site.param1 = _url_decode_slash(locationSearch.param1);
// Hack to decode URL params with Slash (/)
function _url_decode_slash (param) {
if (!param) return param;
param = param.replace(/~2F/g, "/"); // Replace all '~2F' to /
param = param.replace(/%2F/g, "/"); // Replace all '%2F' to /
return param;
}
}
Then in your index.html
<a ui-sref="request.add( {param1: site.param1 } )" >
source to share