Persisting query string with AngularJS routing

前端 未结 6 2207
盖世英雄少女心
盖世英雄少女心 2021-01-05 18:11

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 (sh

6条回答
  •  青春惊慌失措
    2021-01-05 18:37

    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.

提交回复
热议问题