Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting query string with AngularJS routing

Tags:

angularjs

I've been working on a large Angular app for almost a year now and I'm stuck trying to do what I expected to be trivial.

Here are two routes I have with params (shortened for brevity):

/a/:id
/a/:id/b

Let's say the user is at /a/1 and the query string is modified, for example:

/#/a/1?foo=123&bar=456

I want to have a link on the page that directs the user to the second route /a/1/b while maintaining the query string, so the end result is a redirection to:

/#/a/1/b?foo=123&bar=456

I am using Angular 1.2 and the new ngRoute module.

What is the best way to achieve this behavior?


Edit: I should mention I have a working solution right now that seems terrible to me. The link is bound to an ng-click handler which is essentially the following:

$scope.navigateToBClick = function() {
  var path = $location.path() + '/b',
    search = $location.search();
  $location.url(path + '?' + $.param(search));
};
like image 670
Terry Avatar asked Nov 13 '13 19:11

Terry


2 Answers

I'm not sure if you would consider this a better solution than what you've got, but it is a solution.

In your initialization code, add the following:

app.run(["$rootScope", function ($rootScope) {
    $rootScope.$on("$routeChangeSuccess", function (e, current) {
        $rootScope.query = $.param(current.params);
    });
}]);

Then, in your HTML, make your links as follows:

<a ng-href="#/a/{{id}}/b?{{query}}">Navigate to B</a>
like image 84
Lukas Avatar answered Nov 15 '22 09:11

Lukas


If i understand correctly the question then we can solve it with $locationChangeStart $rootScope event. This is done in run phase. Basic idea is : on every location change we will check if we had query string in url (searching for '?' in the url, if there is query string , then we add it to the new url.

    angular.module('your_module').run(function ($rootScope) {
      $rootScope.$on('$locationChangeStart', function (event, newUrl, oldUrl) {

      // If we have queryString on currentURL , then we will add it to the next url
        if(oldUrl.indexOf('?') >= 0) {
         // this can be optimized if we want to check first for queryString in the new url,
         // then append only new params, but that's additional feature.
        newUrl += '?' + oldUrl.split('?')[1];
      }
   });

In HTML we just call $location.path('a/1/b') , url params (query strings) will be added automatically.

like image 44
Buli Avatar answered Nov 15 '22 08:11

Buli