如何在角度路由中传递查询字符串?

时间:2013-03-01 10:49:42

标签: angularjs angularjs-routing

我正在使用AngularJS路由,我正在尝试查看如何使用查询字符串(例如,url.com?key=value)。 Angular不理解包含同名albums的键值对的路由:

angular.module('myApp', ['myApp.directives', 'myApp.services']).config(
        ['$routeProvider', function($routeProvider) {
            $routeProvider.
            when('/albums', {templateUrl: 'albums.html', controller: albumsCtrl}).
            when('/albums?:album_id', {templateUrl: 'album_images.html', controller: albumsCtrl}).
            otherwise({redirectTo: '/home'});
        }],
        ['$locationProvider', function($locationProvider) {
            $locationProvider.html5Mode = true;
        }]
    );

5 个答案:

答案 0 :(得分:63)

路由不适用于查询字符串是正确的,但这并不意味着您在切换路由时不能使用查询字符串在页面之间传递数据!路由参数的明显限制是它们无法在不重新加载页面的情况下进行更新。有时这并不需要,例如在保存新记录之后。原始路由参数为0(表示新记录),现在您要使用通过ajax返回的正确ID更新它,以便在用户刷新页面时,他们会看到新保存的记录。路由参数无法做到这一点,但这可以通过使用查询字符串来实现。

更改路径时不会包含查询字符串,因为这会导致它不匹配路由模板。您可以做的是更改路由,然后应用查询字符串参数。基本上

$location.path('/RouteTemplateName').search('queryStringKey', value).search( ...

这里的美妙之处在于$ routeParams服务将查询字符串值视为与实际路由参数相同,因此您甚至不必更新代码以便以不同方式处理它们。现在,您可以通过在路由定义中包含reloadOnSearch:false来更新参数而无需重新加载页面。

答案 1 :(得分:26)

我认为路由不适用于查询字符串。您可以使用更加RESTful的网址url.com?key=value代替url.com/key/value?,然后您可以按如下方式定义路线:

.when('/albums', ...)
.when('/albums/id/:album_id', ...)

或者

.when('/albums', ...)
.when('/albums/:album_id', ...)

答案 2 :(得分:14)

您可以在searchdocs)中查看$location方法。它允许您向URL添加一些键/值。

例如,$location.search({"a":"b"});将返回此网址:http://www.example.com/base/path?a=b

答案 3 :(得分:2)

使用路线参数

var Ctrl = function($scope, $params) {
  if($params.filtered) {
    //make sure that the ID is there and use a different URL for the JSON data
  }
  else {
    //use the URL for JSON data that fetches all the data
  }
};

Ctrl.$inject = ['$scope', '$routeParams'];

http://docs.angularjs.org/api/ng.$routeParams

答案 4 :(得分:0)

我只能在URL中考虑两个用于查询字符串的用例:

1)如果你需要你的控制器中的查询字符串的键/值对(例如,打印Hello {{name}}并获取查询字符串中的名称,例如?name = John),那么就像Francios所说的那样使用$ location.search你会得到一个querystring作为一个对象({name:John})然后你可以把它放在范围或其他东西(例如$ scope.name = location.search()。name;)。

如果您需要根据查询字符串中的内容重定向到路由器中的另一个页面,例如(?page = Thatpage.htm),那么在您的routerProvider.when()中创建一个redirectTo:它将收到搜索object作为其第三个参数。看看下面的EggHead视频的2:10: http://www.thinkster.io/pick/SzcF8bGeVy/angularjs-redirectto

基本上,redirectTo:function(routeParams,path,search){return search.page}

相关问题