我需要像这样构建 url: /list?filter[status]=1&filter[type]=2
我愿意:
链接:
<a ui-sref="list({filter: {status: 1, type:2}})">List</a>
(在参数中传递复杂对象,如果传递简单对象 - {filter: 1} - 没问题,但我需要这个)
状态:
.state('list', {
url: '/list?filter',
…
})
我总共得到这样的 url:
/list?filter=[object Object]
演示:http://plnkr.co/edit/wV3ieKyc5WGnjqw42p7y?p=preview
我该如何解决?
最佳答案
UI-Router
现在附带了对参数的自定义类型
的支持。有 updated and working version你的笨蛋。
因此,我们可以像这样调整状态定义:
app.config(function($stateProvider) {
$stateProvider.state('list', {
url: 'list?{filter:CoolParam}',
正如我们所见,过滤器现在是 CoolParam
类型。在这里我们将定义它:
app.config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) {
$urlMatcherFactory.type('CoolParam',
{
name : 'CoolParam',
decode: function(val) { return typeof(val) ==="string" ? JSON.parse(val) : val;},
encode: function(val) { return JSON.stringify(val); },
equals: function(a, b) { return this.is(a) && this.is(b)
&& a.status === b.status && a.type == b.type },
is: function(val) { return angular.isObject(val)
&& "status" in val && "type" in val },
})
}]);
现在是像这样的链接的 {{$stateParams}}
:
<a ui-sref="list({filter: {status: 1, type:2}})">Click me to see params</a>
将返回:
{"filter":{"status":1,"type":2}}
注意:在这种情况下,我让我的生活更轻松,只需将 json 转换为字符串。这意味着,url 编码的参数将如下所示:
#/list?filter=%7B%22status%22:1,%22type%22:2%7D
这是 {"status":1,"type":2}
但我们也可以提供其他方式来表达我们的过滤器对象
查一下here
还有相关问答:
- Angular ui router parse query params into booleans
- What is the correct way to use the “bool” param type with ui-router?
因此,上述解决方案可以很好地与作为 JSON 的过滤器一起使用。但是如果我们必须有这样的 url ?filter[status]=1&filter[type]=2
,我们必须以不同的方式定义状态。每个参数都必须声明为单独的简单类型
$stateProvider.state('list2', {
url: 'list2?state&type',
})
但在这种情况下,我们会像这样 ?status=1&type=2
。此映射也是此 plunker 的一部分.
关于javascript - 将复杂对象传递给 ui-sref 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27647367/