americanslon
americanslon

Reputation: 4288

Keep URL params ui-router

I have a web app with an entrance point in a different app. So by the time user gets to my app they have some parameters in the url like so:

http://myapp.com/#/new?param1=value&param2=value2

In my app I have 3-4 tabs each of which is it's own state and is accessed with ui-sref="state"

The issue is that when I switch to any of these states I lose the parameters that user came in with initially.

In a nutshell all I want http://myapp.com/#/differentstate?param1=value&param2=value2 instead of http://myapp.com/#/differentstate when I switch states.

I am not sure how to set that up... Thank you!

Upvotes: 3

Views: 3744

Answers (2)

Milean
Milean

Reputation: 888

Setting $location.search only works while you remain in the same window. To anchor all links, you have to manually extend ui-sref to include the url parameters. Now, your links can be "Open in new Tab" and preserve the parameters. This code also includes a kludge to convert ~2F and %2F to / so your links stay consistent. To do 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 } )" >

Upvotes: 1

TheSharpieOne
TheSharpieOne

Reputation: 25726

inside of your angular app's .run() function you can do this: (you will need to 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);
    });

Upvotes: 10

Related Questions