-->

什么是阅读AngularJS查询参数的最简洁的方式?什么是阅读AngularJS查询参数的最简洁的方

2019-06-17 10:14发布

我想读的使用AngularJS网址查询参数的值。 我访问与以下URL的HTML:

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

正如预期的那样, location.search"?target=bob" 。 为了访问目标的价值,我发现在网络上列出的各种例子,但是没有人在AngularJS 1.0.0rc10工作。 具体而言,以下都是undefined

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

任何人都知道什么工作? (我使用$location作为参数传递给我的控制器)


更新:

我已经发布了以下的解决方案,但我并不完全满意。 在文档开发指南:角服务:使用$位置状态有关以下$location

什么时候应该使用$位置?

任何应用程序需要时间来改变作出反应,当前的URL,或者如果你想改变当前的URL在浏览器中。

对于我的情况,我的网页会从查询参数的外部网页打开,所以我不“反应,在当前URL的变化”本身。 因此,也许$location是不是为作业(丑陋的详情,请参阅我的回答如下)的工具。 因此,我已经改变了这个问题的标题从“如何使用$位置读取AngularJS查询参数?” 对“什么是阅读AngularJS查询参数最简洁的方法是什么?”。 很显然,我可以只使用JavaScript和正则表达式解析location.search ,但去低级别的这么基本的真正冒犯了我的感情程序员的东西。

所以:有使用更好的方法$location比我在我的答案做的,或者是有一个简洁的替代?

Answer 1:

你可以注入$ routeParams (需要ngRoute )到您的控制器。 下面是从文档的例子:

// 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'}

编辑:您还可以获取和使用所设置的查询参数$位置服务(可用ng ),特别是它的search方法: $ location.search() 。

$ routeParams是控制器的初始负荷后不太有用; $location.search()可随时调用。



Answer 2:

好,你已经成功地把它与HTML5模式下工作,但它也有可能使其在hashbang模式下工作。

你可以简单地使用:

$location.search().target

以访问“目标”搜索PARAM。

对于参考,这里是工作的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> 



Answer 3:

为了给出部分答案我自己的问题,这里是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>

关键是要调用$locationProvider.html5Mode(true); 如上完成。 现在打开时,工作http://127.0.0.1:8080/test.html?target=bob 。 我不开心的事实,它不会在旧的浏览器的工作,但我可能仍要使用这种方法。

这将与旧的浏览器中另一种方法是下降的html5mode(true)调用,并与哈希使用下列地址+,而不是削减:

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

相关文件是在开发人员指南:角服务:使用$位置 (奇怪的是,我的谷歌搜索没有找到这个......)。



Answer 4:

它可以通过两种方式来完成:

  1. 使用$routeParams

最佳及推荐解决方案是使用$routeParams到控制器中。 它要求ngRoute要安装的模块。

   function MyController($scope, $routeParams) {
      // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
      // Route: /Chapter/:chapterId/Section/:sectionId
      // $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
      var search = $routeParams.search;
  }
  1. 使用$location.search()

这里有一个警告。 它将与HTML5模式下工作。 默认情况下,它不会为不具有哈希(网址工作# ),则它http://localhost/test?param1=abc&param2=def

你可以把它加入工作#/在URL中。 http://localhost/test#/?param1=abc&param2=def

$location.search()返回一个对象,如:

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


Answer 5:

$ location.search()将只使用HTML5模式打开,只在支持的浏览器。

这将始终工作:

$ window.location.search



Answer 6:

只是为了summerize。

如果您的应用正在从外部链接加载然后角不会检测这是一个URL变化,使$ loaction.search()会给你一个空对象。 为了解决这个问题,你需要设置你的应用程序配置如下(app.js)

.config(['$routeProvider', '$locationProvider', function ($routeProvider,     $locationProvider) 
{
   $routeProvider
      .when('/', {
         templateUrl: 'views/main.html',
         controller: 'MainCtrl'
      })
      .otherwise({
         redirectTo: '/'
      });

      $locationProvider.html5Mode(true);
 }]);


Answer 7:

只是精度埃利斯怀特海的答案。 $locationProvider.html5Mode(true); 将与angularjs的新版本,而不指定的基本URL用于与应用程序不工作<base href="">标记或参数设置requireBasefalse

从文档 :

如果您配置$位置使用html5Mode(history.pushState),你需要指定基本网址与标签的应用程序或配置$ locationProvider不通过传递与requireBase一个定义对象需要一个基础标签:假以$ locationProvider。 html5Mode():

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});


Answer 8:

你也可以使用$位置。$$ search.yourparameter



Answer 9:

这可能有助于uou

什么是阅读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


Answer 10:

我发现,一个SPA HTML5Mode引起了大量的404度错误的问题,这是没有必要作出$ location.search工作在这种情况下。 在我来说,我想捕捉一个URL查询字符串参数,当用户来到我的网站,无论哪个“页”他们最初链接,并能够将其发送到该网页,一旦他们登录。所以,我只是捕获所有在app.run的东西

$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
    if (fromState.name === "") {
        e.preventDefault();
        $rootScope.initialPage = toState.name;
        $rootScope.initialParams = toParams;
        return;
    }
    if ($location.search().hasOwnProperty('role')) {
        $rootScope.roleParameter = $location.search()['role'];
    }
    ...
}

然后登录后后,我可以说$ state.go($ rootScope.initialPage,$ rootScope.initialParams)



Answer 11:

这是一个有点晚了,但我觉得你的问题是,您的网址。 如果不是的

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

你有过

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

我敢肯定它会工作。 角是真的挑剔的#/



文章来源: What's the most concise way to read query parameters in AngularJS?