繁体   English   中英

使用 AngularJS $location 从 URL 中的查询字符串获取值

[英]Getting values from query string in an URL using AngularJS $location

关于$location.search文档说,

不带任何参数调用时,返回当前 url 的搜索部分(作为对象)。

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

不确定自接受的答案被接受以来它是否已经改变,但这是可能的。

$location.search()将返回一个键值对对象,与查询字符串相同。 没有值的键只是作为真存储在对象中。 在这种情况下,对象将是:

{"test_user_bLzgB": true}

您可以直接使用$location.search().test_user_bLzgB访问此值

示例(具有更大的查询字符串): http : //fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

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

编辑:
正如@Naresh 和@DavidTchepak 在评论中指出的那样,还需要正确配置$locationProviderhttps ://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration

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

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

?user=test_user_bLzgB

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

$location.search().user

如果您不想使用键值,例如 ?foo=bar,我建议使用哈希 #test_user_bLzgB ,

并打电话

$location.hash()

将返回“test_user_bLzgB”,这是您希望检索的数据。

附加信息:

如果您使用了查询字符串方法,并且使用 $location.search() 获得了一个空对象,则可能是因为 Angular 使用的是 hashbang 策略而不是 html5 策略...要使其正常工作,请将此配置添加到您的模块

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

首先使 URL 格式正确以获取查询字符串使用对我有用的#?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)在app的module config中配置

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

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

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

参考:

  1. 基本 href="/"
  2. html5模式

Angular 不支持这种查询字符串。

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

根本没有 API 来管理不代表键值对集的查询字符串。

在我的 NodeJS 示例中,我有一个 url "localhost:8080/Lists/list1.html?x1=y",我想遍历并获取值。

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

  1. angular-route.js 的脚本源代码
  2. 将“ngRoute”注入您的应用程序模块的依赖项
  3. 配置您的 locationProvider
  4. 添加 $location 的基本标签(如果不这样做,您的 search().x1 将不返回任何内容或未定义。或者,如果基本标签有错误的信息,您的浏览器将无法在脚本 src 中找到您的文件您的 .html 需要。始终打开页面的查看源来测试您的文件位置!)
  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

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

 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>

很晚的答案:(但是对于有需要的人来说,这对 Angular js 也有效 :) URLSearchParams让我们看看我们如何使用这个新 API 从位置获取值!

// 假设“?post=1234&action=edit”

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

仅供参考:不支持 IE

使用此函数 from 而不是URLSearchParams

urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log(urlParam('action')); //edit

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM