[英]Pass complex object to ui-sref params
I need build url like this: /list?filter[status]=1&filter[type]=2 我需要这样的构建URL: / list?filter [status] = 1&filter [type] = 2
I do: 我做:
<a ui-sref="list({filter: {status: 1, type:2}})">List</a>
(pass complex object in params, if pass simple object - {filter: 1} - it ok, but I need this) (在params传递复杂对象,如果传递简单对象 - {filter:1} - 没关系,但我需要这个)
.state('list', {
url: '/list?filter',
…
})
In total I get url like: 总的来说我得到的网址如下:
/list?filter=[object Object]
Demo: http://plnkr.co/edit/wV3ieKyc5WGnjqw42p7y?p=preview 演示: http : //plnkr.co/edit/wV3ieKyc5WGnjqw42p7y?p=preview
How I can fix it? 我该怎么办呢?
The UI-Router
is now shipped with support for custom types
of params. UI-Router
现在附带了对custom types
的参数的支持。 There is updated and working version of your plunker. 你的plunker有更新和工作版本 。
So, we can adjust the state def like this: 所以,我们可以像这样调整状态def:
app.config(function($stateProvider) {
$stateProvider.state('list', {
url: 'list?{filter:CoolParam}',
As we can see, the filter is now of type CoolParam
. 我们可以看到,过滤器现在是
CoolParam
类型。 Here we will define it: 在这里我们将定义它:
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 },
})
}]);
And now the {{$stateParams}}
of a link like this: 现在这样的链接的
{{$stateParams}}
:
<a ui-sref="list({filter: {status: 1, type:2}})">Click me to see params</a>
will return: 将返回:
{"filter":{"status":1,"type":2}}
NOTE: In this case I made my life easier, and simply converted json into string. 注意:在这种情况下,我让我的生活更轻松,并简单地将json转换为字符串。 This means, that url encoded param will look like this:
这意味着,url编码的param将如下所示:
#/list?filter=%7B%22status%22:1,%22type%22:2%7D
which is {"status":1,"type":2}
这是
{"status":1,"type":2}
But we can provide also other ways how to express our filter object 但我们还可以提供其他方式来表达我们的过滤器对象
Also related Q & A: 还有相关的问答:
So, the above solution is nicely working with filter as a JSON. 所以,上面的解决方案很好地使用filter作为JSON。 But in case that we must have url like this
?filter[status]=1&filter[type]=2
, we have to define the state differently. 但是如果我们必须有这样的url
?filter[status]=1&filter[type]=2
,我们必须以不同的方式定义状态。 Each parameter must be declared as a separated simple type 必须将每个参数声明为单独的简单类型
$stateProvider.state('list2', {
url: 'list2?state&type',
})
But in this case we would have it like this ?status=1&type=2
. 但在这种情况下,我们会这样
?status=1&type=2
。 This mapping is also part of this plunker . 此映射也是此plunker的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.