传递复杂对象的UI SREF PARAMS [英] Pass complex object to ui-sref params

查看:182
本文介绍了传递复杂对象的UI SREF PARAMS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要建立网址是这样的:
/列表筛选[状态] = 1&安培;筛选【类型】= 2

I need build url like this: /list?filter[status]=1&filter[type]=2

我做的:

<一个UI的SREF =列表({过滤器:{状态:1,类型:2}})>清单< / A>

(传递复杂对象的参数,可以传递,如果简单的对象 - {过滤器: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-路由器现在随支持的 自定义类型 则params的。有更新,您plunker的工作版本

因此​​,我们可以调整状态DEF是这样的:

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}} 像这样的链接:

<a ui-sref="list({filter: {status: 1, type:2}})">Click me to see params</a>

将返回:

{"filter":{"status":1,"type":2}}

注:在这种情况下,我做了我的生活更轻松,简单地转换成JSON字符串。这意味着,URL连接codeD参数看起来是这样的:

#/list?filter=%7B%22status%22:1,%22type%22:2%7D

{身份:1,型:2}

但是,我们可以也提供其他的方式如何前preSS我们的过滤对象

检查一下这里

也与Q&安培;答:

  • Angular ui router parse query params into booleans
  • What is the correct way to use the "bool" param type with ui-router?

所以,上述解决方案很好地与过滤器作为JSON工作。 ?但如果我们必须有URL这样的过滤器[状态] = 1&安培;筛选【类型】= 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',
})

但是,在这种情况下,我们将不得不像这样状态= 1&放大器;类型= 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 PARAMS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆