将复杂对象传递给 ui-sref 参数

2024-05-27

我需要这样的构建网址:/列表?过滤器[状态]=1&过滤器[类型]=2

I do:

link:

<a ui-sref="list({filter: {status: 1, type:2}})">List</a>

(在参数中传递复杂对象,如果传递简单对象 - {filter: 1} - 可以,但我需要这个)

state:

.state('list', {
    url:        '/list?filter',
    …
})

总的来说,我得到的网址如下:

/list?filter=[object Object]

Demo: http://plnkr.co/edit/wV3ieKyc5WGnjqw42p7y?p=preview http://plnkr.co/edit/wV3ieKyc5WGnjqw42p7y?p=preview

我该如何修复它?


The UI-Router现已支持custom types参数。有更新和工作版本 http://plnkr.co/edit/VwowXoPBc0VWm6ZY8NFc?p=preview你的笨蛋。

因此,我们可以这样调整状态 def:

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 http://plnkr.co/edit/VwowXoPBc0VWm6ZY8NFc?p=preview

还有相关问答:

  • Angular ui 路由器将查询参数解析为布尔值 https://stackoverflow.com/a/27422981/1679310
  • 在 ui-router 中使用“bool”参数类型的正确方法是什么? https://stackoverflow.com/a/27182177/1679310

因此,上述解决方案可以很好地使用 JSON 格式的过滤器。但如果我们必须有这样的网址?filter[status]=1&filter[type]=2,我们必须以不同的方式定义状态。每个参数必须声明为单独的简单类型

$stateProvider.state('list2', {
    url: 'list2?state&type',
})

但在这种情况下我们会这样?status=1&type=2。此映射也是此的一部分plunker http://plnkr.co/edit/VwowXoPBc0VWm6ZY8NFc?p=preview.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将复杂对象传递给 ui-sref 参数 的相关文章

随机推荐