使用AngularJS解析查询字符串而不使用html5mode的最佳方法

End*_*050 31 javascript angularjs

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

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

http://localhost/test?param1=abc&param2=def
http://localhost/test#/param1=abc&param2=def
Run Code Online (Sandbox Code Playgroud)

$ 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

}]);
Run Code Online (Sandbox Code Playgroud)

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

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

我看过这篇文章并没有找到解决方案.我肯定错过了什么.谢谢您的帮助.

Aus*_*eco 32

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

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

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

{
  param1: 'abc',
  param2: 'def'
}
Run Code Online (Sandbox Code Playgroud)

  • 唉 - 我没有意识到你需要#和?这完全有道理 - 谢谢! (2认同)