本文翻译自:What's the most concise way to read query parameters in AngularJS?

I'd like to read the values of URL query parameters using AngularJS. 我想使用AngularJS读取URL查询参数的值。 I'm accessing the HTML with the following URL: 我正在使用以下URL访问HTML:

http://127.0.0.1:8080/test.html?target=bob

As expected, location.search is "?target=bob" . 不出所料, location.search"?target=bob" For accessing the value of target , I've found various examples listed on the web, but none of them work in AngularJS 1.0.0rc10. 为了访问target的值,我在网络上找到了各种示例,但是在AngularJS 1.0.0rc10中它们都不起作用。 In particular, the following are all undefined : 特别是,以下所有内容均未undefined

  • $location.search.target
  • $location.search['target']
  • $location.search()['target']

Anyone know what will work? 有人知道会起作用吗? (I'm using $location as a parameter to my controller) (我将$location用作控制器的参数)


Update: 更新:

I've posted a solution below, but I'm not entirely satisfied with it. 我在下面发布了一个解决方案,但是我并不完全满意。 The documentation at Developer Guide: Angular Services: Using $location states the following about $location : 开发人员指南:Angular Services:使用$ location中的文档说明了有关$location的以下内容:

When should I use $location? 什么时候应该使用$ location?

Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser. 任何时候您的应用程序需要对当前URL的更改做出反应,或者您想在浏览器中更改当前URL。

For my scenario, my page will be opened from an external webpage with a query parameter, so I'm not "reacting to a change in the current URL" per se. 对于我的情况,我的页面将从带有查询参数的外部网页打开,因此,我本身并不是在“响应当前URL的更改”。 So maybe $location isn't the right tool for the job (for the ugly details, see my answer below). 因此, $location可能不是工作的正确工具(有关丑陋的详细信息,请参见下面的答案)。 I've therefore changed the title of this question from "How to read query parameters in AngularJS using $location?" 因此,我已将问题的标题从“如何使用$ location读取AngularJS中的查询参数?”中更改。 to "What's the most concise way to read query parameters in AngularJS?". “在AngularJS中读取查询参数的最简洁方法是什么?”。 Obviously I could just use javascript and regular expression to parse location.search , but going that low-level for something so basic really offends my programmer sensibilities. 显然,我可以只使用javascript和正则表达式来解析location.search ,但是以如此低的水平进行一些基本的操作确实会冒犯我的程序员。

So: is there a better way to use $location than I do in my answer, or is there a concise alternate? 所以:有比我在答案中更好的使用$location方法,还是有简洁的替代方法?


#1楼

参考:https://stackoom.com/question/kQAL/在AngularJS中读取查询参数的最简洁方法是什么


#2楼

You can inject $routeParams (requires ngRoute ) into your controller. 您可以将$ routeParams (需要ngRoute )注入到控制器中。 Here's an example from the docs: 这是文档中的示例:

// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}

EDIT: You can also get and set query parameters with the $location service (available in ng ), particularly its search method: $location.search() . 编辑:您还可以使用$ location服务(在ng可用)来获取和设置查询参数,尤其是其search方法: $ location.search() 。

$routeParams are less useful after the controller's initial load; 控制器初始加载后,$ routeParams的用处不大。 $location.search() can be called anytime. $location.search()可以随时调用。


#3楼

To give a partial answer my own question, here is a working sample for HTML5 browsers: 为了部分回答我自己的问题,以下是HTML5浏览器的工作示例:

<!DOCTYPE html>
<html ng-app="myApp">
<head><script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script><script>angular.module('myApp', [], function($locationProvider) {$locationProvider.html5Mode(true);});function QueryCntl($scope, $location) {$scope.target = $location.search()['target'];}</script>
</head>
<body ng-controller="QueryCntl">Target: {{target}}<br/></body>
</html>

The key was to call $locationProvider.html5Mode(true); 关键是调用$locationProvider.html5Mode(true); as done above. 如上所述。 It now works when opening http://127.0.0.1:8080/test.html?target=bob . 现在,在打开http://127.0.0.1:8080/test.html?target=bob I'm not happy about the fact that it won't work in older browsers, but I might use this approach anyway. 我对它不能在较旧的浏览器中运行这一事实感到不满意,但是我仍然可以使用这种方法。

An alternative that would work with older browsers would be to drop the html5mode(true) call and use the following address with hash+slash instead: 与较旧的浏览器一起使用的另一种方法是删除html5mode(true)调用,并将以下地址改为使用hash + slash:

http://127.0.0.1:8080/test.html#/?target=bob

The relevant documentation is at Developer Guide: Angular Services: Using $location (strange that my google search didn't find this...). 相关文档位于开发人员指南:Angular Services:使用$ location (奇怪的是,我的Google搜索未找到此...)。


#4楼

Good that you've managed to get it working with the html5 mode but it is also possible to make it work in the hashbang mode. 很好,您已经设法使其在html5模式下工作,但也可以使其在hashbang模式下工作。

You could simply use: 您可以简单地使用:

$location.search().target

to get access to the 'target' search param. 可以访问“目标”搜索参数。

For the reference, here is the working jsFiddle: http://web.archive.org/web/20130317065234/http://jsfiddle.net/PHnLb/7/ 供参考,这里是工作中的jsFiddle: http ://web.archive.org/web/20130317065234/http://jsfiddle.net/PHnLb/7/

 var myApp = angular.module('myApp', []); function MyCtrl($scope, $location) { $scope.location = $location; $scope.$watch('location.search()', function() { $scope.target = ($location.search()).target; }, true); $scope.changeTarget = function(name) { $location.search('target', name); } } 
 <div ng-controller="MyCtrl"> <a href="#!/test/?target=Bob">Bob</a> <a href="#!/test/?target=Paul">Paul</a> <hr/> URL 'target' param getter: {{target}}<br> Full url: {{location.absUrl()}} <hr/> <button ng-click="changeTarget('Pawel')">target=Pawel</button> </div> 

#5楼

您还可以使用$ location。$$ search.yourparameter


#6楼

this may help uou 这可能会帮助你

What's the most concise way to read query parameters in AngularJS 在AngularJS中读取查询参数的最简洁方法是什么

// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}<!DOCTYPE html>
<html ng-app="myApp">
<head><script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script><script>angular.module('myApp', [], function($locationProvider) {$locationProvider.html5Mode(true);});function QueryCntl($scope, $location) {$scope.target = $location.search()['target'];}</script>
</head>
<body ng-controller="QueryCntl">Target: {{target}}<br/></body>
</html>($location.search()).target

在AngularJS中读取查询参数的最简洁方法是什么?相关推荐

  1. 获取request中的查询参数

    //获取request中的查询参数public static Map<String, Object> getRequestParamsByMap(HttpServletRequest re ...

  2. 【Spring Boot】从配置文件中读取配置参数

    前言 在生产环境中,经常会用到各种各样的参数,为了避免代码太过死板,一般将参数写入配置文件,然后需要用到参数的时候从配置文件中读取,下面总结出几种从配置文件中读取配置参数的方法. 环境搭建 现有配置文 ...

  3. jmeter参数值只读取了第一个_Jmeter学习笔记-从文本中读取一个参数,多个值(7)...

    测试场景:插入多条数据时,某些关键字不能重复,从文件中读取其参数,可解决该问题. 1.CSV Data set config的配置如下图: Filename:需要传入的参数所位于的文件名称,一定要填写 ...

  4. Struts2中action接收参数的三种方法及ModelDriven跟Preparable接口结合JAVA反射机制的灵活用法...

    Struts2中action接收参数的三种方法及ModelDriven跟Preparable接口结合JAVA反射机制的灵活用法 www.MyException.Cn   发布于:2012-09-15 ...

  5. php中读取文件内容的几种方法。(file_get_contents:将文件内容读入一个字符串)...

    php中读取文件内容的几种方法.(file_get_contents:将文件内容读入一个字符串) 一.总结 php中读取文件内容的几种方法(file_get_contents:将文件内容读入一个字符串 ...

  6. 文件_ _android从资源文件中读取文件流并显示的方法

    ======== 1   android从资源文件中读取文件流并显示的方法. 在android中,假如有的文本文件,比如TXT放在raw下,要直接读取出来,放到屏幕中显示,可以这样: private ...

  7. matlab中读文件的行数_Matlab中读取txt文件的几种方法

    Matlab中读取txt文件的几种方法 一.纯数据文件(没有字母和中文,纯数字) 对于这种txt文档,从matalb中读取就简单多了 例如test.txt文件,内容为"17.901 -1.1 ...

  8. 解惑(三)----- 深入理解Python中的self参数和__init__(self)方法--通过类比Java语言

    一.前言 在这里我想通过用Python和Java语言的类比来对Python中的self参数和__init__(self)方法做一个深入的解释.这样可以加深对self参数和__init__(self)方 ...

  9. java property xml,Java开发中读取XML与properties配置文件的方法

    相关阅读: 1. XML文件: 什么是XML?XML一般是指可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言. 2.XML文件的优点: 1)XML文档内容和结构完 ...

最新文章

  1. javascript读取XML文档
  2. echarts geo地图示例_干货|Pyecharts绘制好看的交互式地图教程
  3. linux 外部协议请求,ARM架构和总线协议如何支持Linux原子操作?
  4. 流式计算框架Storm网站访问来源实时统计及存储到redis代码示例
  5. 2019牛客暑期多校训练营(第三场)F - Planting Trees (枚举 + 单调队列)
  6. sqlserver中的通配符
  7. Cannot convert type ‘ASP.login_aspx’ to ‘System.Web.UI.WebControls.Login’的解决方法
  8. Redmine Gantt 实现 (Show relations in Gantt diagram)
  9. java leader 选举_简述ZK的fastleaderelection选举leader的算法
  10. Eclipse下Maven工程多模块继承和聚合的创建
  11. mac 下安装 lua5.3 + cjson
  12. Algo: Basic
  13. WCF分布式开发常见错误(17):无法启动MSMQ服务
  14. w讠ndows Boot Manager,开机出现windows boot manager的解决方法和步骤(图文教程)
  15. con 元器件符号_protel中常用元件电器符号
  16. 2019强网杯部分writeup
  17. 使用gpu服务器搭建人脸识别系统,人脸识别gpu服务器配置
  18. Mysql培训第二天
  19. Arduion实验九 轻触开关实验
  20. 切片和切块 钻取 旋转

热门文章

  1. .Net定时弹出窗口(c#)
  2. Reconstruct binary tree
  3. Android初始化过程
  4. android xml 文件里面的宽度Match_Parent 被 替换成了wrap_content
  5. Service ANR问题
  6. 源码里throw new RuntimeException(“Stub!“)什么意思
  7. 组件化开发和模块化开发概念辨析
  8. (0062)iOS开发之Xcode自带单元测试UnitTest
  9. 北风设计模式课程---单一职责原则
  10. C#定时清理内存,net网页端可以尝试使用