将复杂对象传递给 ui-sref 参数 [英] Pass complex object to ui-sref params
问题描述
我需要像这样构建网址:/list?filter[status]=1&filter[type]=2
I need build url like this: /list?filter[status]=1&filter[type]=2
我愿意:
(在参数中传递复杂对象,如果传递简单对象 - {filter: 1} - 没关系,但我需要这个)
(pass complex object in params, if pass simple object - {filter: 1} - it ok, but I need this)
.state('list', {
url: '/list?filter',
…
})
总的来说,我得到的网址如下:
In total I get url like:
/list?filter=[object Object]
演示:http://plnkr.co/edit/wV3ieKyc5WGnjqw42p7y?p=preview
我该如何解决?
推荐答案
UI-Router
现在支持自定义类型
参数.您的 plunker 有更新和工作版本.
所以,我们可以这样调整状态定义:
So, we can adjust the state def like this:
app.config(function($stateProvider) {
$stateProvider.state('list', {
url: 'list?{filter:CoolParam}',
如我们所见,过滤器现在属于 CoolParam
类型.这里我们将定义它:
As we can see, the filter is now of type 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 },
})
}]);
现在是这样一个链接的{{$stateParams}}
:
And now the {{$stateParams}}
of a link like this:
<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}
但是我们也可以提供其他方式来表达我们的过滤器对象
在这里
还有相关问答答:
因此,上述解决方案可以很好地将过滤器作为 JSON 使用.但是如果我们必须有像这样的 url ?filter[status]=1&filter[type]=2
,我们必须以不同的方式定义状态.每个参数必须声明为单独的简单类型
So, the above solution is nicely working with filter as a JSON. But in case that we must have url like this ?filter[status]=1&filter[type]=2
, we have to define the state differently. Each parameter must be declared as a separated simple type
$stateProvider.state('list2', {
url: 'list2?state&type',
})
但在这种情况下,我们会像这样 ?status=1&type=2
.此映射也是此 plunker 的一部分.
But in this case we would have it like this ?status=1&type=2
. This mapping is also part of this plunker.
这篇关于将复杂对象传递给 ui-sref 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!