本文介绍了AngularJS:获取查询字符串值,而不在链接的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让使用angularjs查询字符串值。

I am trying to get query string values using angularjs.

我的网址: HTTP://localhost/example.php sportsId = 3

应用时,我 VAR转到= $ location.search()['sportsId'];
它返回我不确定。

when I applied var goto = $location.search()['sportsId'];it returns me undefined.

不过,如果我在URL添加哈希像的URL:http://localhost/example.php# sportsId = 3

However, if I add hash in url like Url: http://localhost/example.php#?sportsId=3

然后我返回正确的值3。

then it returns me correct value 3.

但在这种情况下,它也给了我错误:[$解析:语法] http://errors.angularjs.org/1.3.8/$parse/syntax?p0=undefined&p1=not%20a%20primary%20ex$p$pssion&p2=null&p3=sportsID%3D&p4=sportsID%3D

But in this case, it also gives me Error: [$parse:syntax] http://errors.angularjs.org/1.3.8/$parse/syntax?p0=undefined&p1=not%20a%20primary%20expression&p2=null&p3=sportsID%3D&p4=sportsID%3D

另外,我的默认 $ _ REQUEST ['sportsId'] 不与哈希格式工作。

Also, my default $_REQUEST['sportsId'] is not working with hash format.

我该如何正确使用angularjs获得查询字符串值?

How can I correctly get values from query string by using angularjs?

推荐答案

我知道这是不是角,但其纯JS和工作就像一个魅力(只是不添加dummyPath,它会采取URL)。

I know this is not Angular but its pure JS and works like a charm (just don't add dummyPath and it will take the URL).

function getUrlParameter(param, dummyPath) {
        var sPageURL = dummyPath || window.location.search.substring(1),
            sURLVariables = sPageURL.split(/[&||?]/),
            res;

        for (var i = 0; i < sURLVariables.length; i += 1) {
            var paramName = sURLVariables[i],
                sParameterName = (paramName || '').split('=');

            if (sParameterName[0] === param) {
                res = sParameterName[1];
            }
        }

        return res;
}

用法:

var sportdsId = getUrlParameter('sportsId');

这篇关于AngularJS:获取查询字符串值,而不在链接的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 17:00