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.