41

在 Angularjs 应用程序中,我有一个类似
http://url.com/my_app/#/store/items.
现在我想附加查询字符串,例如
http://url.com/my_app/#/store/items?page=2.

但在 url 中,javascript 对"?" to "%3F"我不想要的进行编码。它应该保留“?” 仅在 url 中,因为 angularjs $location.search() 不为“%3F”返回任何内容。

怎么做?

4

5 回答 5

83

您的问题中没有足够的细节,所以我假设您在非 HTML5 模式下使用 AngularJS 路由 - 或至少$location 服务。如果是这样,#从单页应用程序的角度来看,字符后面的部分代表您的 URL(更多关于 AngularJS 的信息)。

如果上述假设是正确的,则意味着您不应尝试“手动”添加或操作问号。相反,您应该更改要操作查询字符串的部分(之后search的部分),并且问号将根据需要添加/删除到最终 URL。$location?

在你的情况下,你可以写:

$location.path('/store/items').search('page', 2)

这是假设您正在从 JavaScript 操作 URL,如您的问题中所述。

于 2013-03-04T16:23:41.397 回答
24

如果您使用的是 $location 服务,请$location.url('/store/items?page=2')改用。这是至少从 1.0.7 开始的 setter 方法,并且在我的 1.1.5 应用程序中很有效。

于 2014-01-09T12:52:45.980 回答
3

您可以创建一个参数对象,例如:

var param = {
    page: 2
}
$location.url("/store/items").search(param)
于 2015-05-05T12:11:45.030 回答
1

如果您使用的是强烈推荐的ui-router,您可以$state.go(to, params, options)按照此处所述使用。

作为先决条件,您需要正确定义您的状态,这意味着必须让 ui-router 知道每个可能的查询参数。请参阅以下示例(pageotherParam):

$stateProvider.
state('storeItems', {
  url: '/store/items?page&otherParam',
  templateUrl: '/modules/store/views/item.client.view.html'
});

然后你可以通过调用例如从控制器切换位置

$scope.gotoItemsPage = function(page) {
  $state.go('storeItems', {
    page: page,
    otherParam: 'Just a show off'
  });
};

无需摆弄所需的编码和高度可读性!

于 2015-01-04T17:30:01.797 回答
-3

您可以使用decodeURIComponent

例如:

decodeURIComponent('http://url.com/my_app/#/store/items%3Fpage=2');
// will give you `http://url.com/my_app/#/store/items?page=2`
于 2013-03-04T09:06:43.743 回答