在 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”返回任何内容。
怎么做?
5 回答
您的问题中没有足够的细节,所以我假设您在非 HTML5 模式下使用 AngularJS 路由 - 或至少$location 服务。如果是这样,#
从单页应用程序的角度来看,字符后面的部分代表您的 URL(更多关于 AngularJS 的信息)。
如果上述假设是正确的,则意味着您不应尝试“手动”添加或操作问号。相反,您应该更改要操作查询字符串的部分(之后search
的部分),并且问号将根据需要添加/删除到最终 URL。$location
?
在你的情况下,你可以写:
$location.path('/store/items').search('page', 2)
这是假设您正在从 JavaScript 操作 URL,如您的问题中所述。
如果您使用的是 $location 服务,请$location.url('/store/items?page=2')
改用。这是至少从 1.0.7 开始的 setter 方法,并且在我的 1.1.5 应用程序中很有效。
您可以创建一个参数对象,例如:
var param = {
page: 2
}
$location.url("/store/items").search(param)
如果您使用的是强烈推荐的ui-router,您可以$state.go(to, params, options)
按照此处所述使用。
作为先决条件,您需要正确定义您的状态,这意味着必须让 ui-router 知道每个可能的查询参数。请参阅以下示例(page
和otherParam
):
$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'
});
};
无需摆弄所需的编码和高度可读性!
您可以使用decodeURIComponent。
例如:
decodeURIComponent('http://url.com/my_app/#/store/items%3Fpage=2');
// will give you `http://url.com/my_app/#/store/items?page=2`