【问题标题】:Best way to parse a query string with AngularJS without using html5mode在不使用 html5mode 的情况下使用 AngularJS 解析查询字符串的最佳方法
【发布时间】:2014-01-08 15:38:10
【问题描述】:

使用 html5mode 在 Angular without 中解析查询字符串的最佳方法是什么? (不使用 html5mode,因为我们需要支持旧版浏览器

无论我是否使用哈希,我都会得到相同的未定义结果:

http://localhost/test?param1=abc&param2=def
http://localhost/test#/param1=abc&param2=def

$routeParams 和 $location.search() 都返回 undefined:

var app = angular.module('plunker', ["ngRoute"]);

app.controller('MainCtrl', ["$scope", "$routeParams", "$location",
  function($scope, $routeParams, $location) {

  console.log($routeParams, $routeParams.abc); //undefined, undefined
  console.log($location.search(), $location.search().abc); //undefined, undefined

}]);

我可以自己解析 window.location.search,但我希望在 Angular 中有更好的方法。

Plnkr:http://plnkr.co/edit/alBGFAkfqncVyK7iv8Ia?p=preview

我已阅读 this post 并没有找到解决方案。我肯定错过了什么。感谢您的帮助。

【问题讨论】:

  • 所以你的 plunker 的问题可能是因为它在 iframe 中。本地是否发生同样的问题?
  • 是的,本地结果相同。感谢您的帮助。

标签: javascript angularjs


【解决方案1】:

查询参数应该放在哈希之后:

http://localhost/test#/?param1=abc&param2=def

这应该允许$location.search() 返回一个像这样的对象:

{
  param1: 'abc',
  param2: 'def'
}

【讨论】:

  • 啊 - 我没有意识到你需要 # 和 ?。这完全有道理 - 谢谢!
  • 或者干脆你可以使用$routeParams
猜你喜欢
  • 2012-04-24
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多