AngularJS: Get query string values without a hash in the link

前端 未结 6 1170
逝去的感伤
逝去的感伤 2020-12-29 09:12

I am trying to get query string values using angularjs.

my Url: http://localhost/example.php?sportsId=3

when I applied var goto = $locati

6条回答
  •  我在风中等你
    2020-12-29 09:27

    Create your self a search object from the the $window.location.search property using the following:

        var search = $window.location.search
                .split(/[&||?]/)
                .filter(function (x) { return x.indexOf("=") > -1; })
                .map(function (x) { return x.split(/=/); })
                .map(function (x) {
                    x[1] = x[1].replace(/\+/g, " ");
                    return x;
                })
                .reduce(function (acc, current) {
                    acc[current[0]] = current[1];
                    return acc;
                }, {});
    
        var sportsId = search.sportsId;
    

    or create a queryString factory which you can use anywhere.. This combines the left and right parts of the queryString.. I.e. before # and after the #

    (function () {
        "use strict";
    
        angular
            .module("myModuleName")
            .factory("queryString", QueryStringFactory);
    
        function QueryStringFactory($window, $location) {
    
            function search() {
    
                var left = $window.location.search
                    .split(/[&||?]/)
                    .filter(function (x) { return x.indexOf("=") > -1; })
                    .map(function (x) { return x.split(/=/); })
                    .map(function (x) {
                        x[1] = x[1].replace(/\+/g, " ");
                        return x;
                    })
                    .reduce(function (acc, current) {
                        acc[current[0]] = current[1];
                        return acc;
                    }, {});
    
                var right = $location.search() || {};
    
                var leftAndRight = Object.keys(right)
                    .reduce(function(acc, current) {
                        acc[current] = right[current];
                        return acc;
                    }, left);
    
                return leftAndRight;
            }
    
            return {
                search: search
            };
    
        }
    
    }());
    

    usage:

    var qs = queryString.search();
    var sportsId = sq.sportsId;
    

提交回复
热议问题