使用AngularJS $ location从URL中获取查询string的值

对于$ location.search, 文档说,

当没有任何参数调用时返回当前URL的search部分(作为对象)。

在我的url中,我的查询string有一个没有值的参数'test_user_bLzgB'。 另外'$ location.search()'返回一个对象。 我如何得到实际的文字?

不知道自接受答案被接受以来是否发生了变化,但这是可能的。

$location.search()将返回键值对的对象,与查询string相同。 没有任何值的键只是存储在对象中。 在这种情况下,该对象将是:

 {"test_user_bLzgB": true} 

你可以直接用$location.search().test_user_bLzgB来访问这个值

示例(查询string较大): http : //fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

注意:由于哈希(因为它会去http://fiddle.jshell.net/#/url ,这将创build一个新的小提琴),这个小提琴不会工作在不支持js历史的浏览器(不会工作在IE 10中)

编辑:
正如@Naresh和@DavidTchepak的评论所指出的那样, $locationProvider也需要正确configuration: https ://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration

如果您只需要将查询string视为文本,则可以使用: $window.location.search

$location.search()返回一个对象,它由作为variables的键和作为其值的键组成。 所以:如果你这样写你的查询string:

 ?user=test_user_bLzgB 

你可以很容易地得到这样的文字:

 $location.search().user 

如果你不想使用一个键,像?foo = bar这样的值,我build议使用一个哈希#test_user_bLzgB,

并打电话

 $location.hash() 

会返回“test_user_bLzgB”这是你​​想要检索的数据。

附加信息:

如果您使用查询string方法,并且您正在使用$ location.search()获取一个空对象,那么可能是因为Angular使用的是hashbang策略而不是html5的策略。为了使它工作,请将此configuration添加到您的模

 yourModule.config(['$locationProvider', function($locationProvider){ $locationProvider.html5Mode(true); }]); 

首先使URL格式正确,以使查询string使用#?q =string适合我

 http://localhost/codeschool/index.php#?foo=abcd 

将$ location服务注入控制器

 app.controller('MyController', [ '$location', function($location) { var searchObject = $location.search(); // $location.search(); reutrn object // searchObject = { foo = 'abcd' }; alert( searchObject.foo ); } ]); 

所以输出应该是abcd

你也可以使用这个

 function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } var queryValue = getParameterByName('test_user_bLzgB'); 

如果你的$location.search()不工作,那么确保你有以下几点:

1) html5Mode(true)是在应用程序的模块configuration中configuration的

 appModule.config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode(true); }]); 

2) <base href="/">存在于你的HTML中

 <head> <base href="/"> ... </head> 

参考文献:

  1. 基地href =“/”
  2. html5Mode

Angular不支持这种查询string。

URL的查询部分应该是一个&分离的键值对”序列,因此可以完美地解释为一个对象。

根本没有API来pipe理不代表键值对的查询string。

在我的NodeJS的例子中,我有一个URL“localhost:8080 / Lists / list1.html?x1 = y”,我想要遍历和获取值。

为了使用$ location.search()来获得x1 = y,我做了一些事情

  1. 脚本源到angular-route.js
  2. 将'ngRoute'注入到您的应用程序模块的依赖项中
  3. configuration你的locationProvider
  4. 为$ location添加基本标记(如果不这样做,search()。x1将不会返回任何内容或未定义。或者如果base标记具有错误信息,则浏览器将无法在脚本src中find您的文件总是打开页面的视图源来testing你的文件位置!
  5. 调用位置服务(search())

我的list1.js有

  var app = angular.module('NGApp', ['ngRoute']); //dependencies : ngRoute app.config(function ($locationProvider) { //config your locationProvider $locationProvider.html5Mode(true).hashPrefix(''); }); app.controller('NGCtrl', function ($scope, datasvc, $location) {// inject your location service //var val = window.location.href.toString().split('=')[1]; var val = $location.search().x1; alert(val); $scope.xout = function () { datasvc.out(val) .then(function (data) { $scope.x1 = val; $scope.allMyStuffs = data.all; }); }; $scope.xout(); }); 

和我的list1.html有

 <head> <base href="."> </head> <body ng-controller="NGCtrl"> <div>A<input ng-model="x1"/><br/><textarea ng-model="allMyStuffs"/></div> <script src="../js/jquery-2.1.4.min.js"></script> <script src="../js/jquery-ui.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script> <script src="../js/bootstrap.min.js"></script> <script src="../js/ui-bootstrap-tpls-0.14.3.min.js"></script> <script src="list1.js"></script> </body> 

指南: https : //code.angularjs.org/1.2.23/docs/guide/$location

我的修复更简单,创build一个工厂,并作为一个variables实现。 例如

 angular.module('myApp', []) // This a searchCustom factory. Copy the factory and implement in the controller .factory("searchCustom", function($http,$log){ return { valuesParams : function(params){ paramsResult = []; params = params.replace('(', '').replace(')','').split("&"); for(x in params){ paramsKeyTmp = params[x].split("="); // Si el parametro esta disponible anexamos al vector paramResult if (paramsKeyTmp[1] !== '' && paramsKeyTmp[1] !== ' ' && paramsKeyTmp[1] !== null){ paramsResult.push(params[x]); } } return paramsResult; } } }) .controller("SearchController", function($scope, $http,$routeParams,$log,searchCustom){ $ctrl = this; var valueParams = searchCustom.valuesParams($routeParams.value); valueParams = valueParams.join('&'); $http({ method : "GET", url: webservice+"q?"+valueParams }).then( function successCallback(response){ data = response.data; $scope.cantEncontrados = data.length; $scope.dataSearch = data; } , function errorCallback(response){ console.log(response.statusText); }) }) 
 <html> <head> </head> <body ng-app="myApp"> <div ng-controller="SearchController"> <form action="#" > <input ng-model="param1" placeholder="param1" /> <input ng-model="param2" placeholder="param2"/> <!-- Implement in the html code (param1={{param1}}&param2={{param2}}) -> this is a one variable, the factory searchCustom split and restructure in the array params --> <a href="#seach/(param1={{param1}}&param2={{param2}})"> <buttom ng-click="searchData()" >Busqueda</buttom> </a> </form> </div> </body>