最近, 项目开发正在进行时, 心有点燥, 许多东西没来得及去研究, 今天正想问题呢, 同事问到如何获取 url 中的参数, 我一时半会还真没想起来, 刚刚特意研究了一下, 常用的方法就以下几种:
1. 获取当前完整的 url 路径
var absurl = $location.absUrl(); //http://88:8100/#/homePage?id=10&a=100
2. 获取当前 url 路径(当前 url# 后面的内容, 包括参数和哈希值)
var url = $location.url(); ///homePage?id=10&a=100
3. 获取当前 url 的子路径(也就是当前 url# 后面的内容, 不包括参数)
var pathUrl = $location.path() ///homePage
4. 获取当前 url 的协议(比如 http,https)
var protocol = $location.protocol(); //http
5. 获取主机名
var localhost = $location.host(); //88
6. 获取当前 url 的端口
var port = $location.port(); //8100
7. 获取当前 url 的哈希值
var hash = $location.hash() //http://088
8. 获取当前 url 的参数的序列化 json 对象
var search = $location.search(); //{id: "10", a: "100"}
9. 获取 url 参数
- $location.search().name;
- $location.search()['name'];
10. 注意问题
如果是这样的地址: http://lele.sina.com?name=haha
需要在项目中注入 $locationProvider 服务
- var searchApp = angular.module('searchApp', []);
- searchApp.config(['$locationProvider', function($locationProvider) {
- $locationProvider.html5Mode(true);
- }]);
- searchApp.controller('MainCtrl', ['$scope', '$location', function($scope, $location) {
- if ($location.search().keyword) {
- $scope.keyword = $location.search().keyword;
- }
- }]);
11.js 中获取地址栏参数的方法(附加)
- url = https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=娃哈哈
- console.log(window.location.href ); // "https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=娃哈哈"
- console.log(window.location.host); // "www.baidu.com"
- console.log(window.location.pathname); // "/s"
- console.log(window.location.protocol); // "https:"
- console.log(window.location.search); // "?ie=utf-8&f=3&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=娃哈哈"
来源: http://www.jb51.net/article/144947.htm