Angularjs $location service apparently not parsing url?

前端 未结 5 1724
你的背包
你的背包 2020-12-09 01:53

I\'m using angular in an application which is, basically, a table with search results. Access to this table can be achieved via an url like http://myapp/?client=clien

相关标签:
5条回答
  • 2020-12-09 02:24

    When I encountered this problem, another thing that worked for me besides setting the configuration is to add "#" in front of the query string.

    So if you are the one creating the query string, then changing
    myapp/?client=clientName
    to
    myapp/#?client=clientName

    allowed $location.search() to give me a non-empty object which you can then access each parameter using $location.search()['client']

    0 讨论(0)
  • 2020-12-09 02:28

    If you don't want to specify the base tag, you can specify require base false.

    myapp.config(function($locationProvider) {
        $locationProvider.html5Mode({
          enabled: true,
          requireBase: false
        });
    });
    
    0 讨论(0)
  • 2020-12-09 02:39

    The API for $location.search is pretty confusing. Calling

    $location.search('client');
    

    will set the search object to {client: true} and return $location. Furthermore, you have a typo client instead of 'client', so it's setting search to an empty object. So you probably want:

    url += '&client=' + $location.search()['client'];
    
    0 讨论(0)
  • 2020-12-09 02:43

    I was having the same problem before I configured $locationProvider in my app's module config:

    appModule.config(['$locationProvider', function($locationProvider) {
            $locationProvider.html5Mode(true);
        }]);
    
    0 讨论(0)
  • 2020-12-09 02:49

    You can write a function that parses the $window.location.search based on this comment https://github.com/angular/angular.js/issues/7239#issuecomment-42047533

    function parseLocation(location) {
        var pairs = location.substring(1).split("&");
        var obj = {};
        var pair;
        var i;
    
        for (i in pairs) {
            if (pairs[i] === "")
                continue;
    
            pair = pairs[i].split("=");
            obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
        }
    
        return obj;
    }
    
    $scope.query = parseLocation($window.location.search)['query'];
    
    0 讨论(0)
提交回复
热议问题