ami*_*mit 4 angularjs angular-ui-router
考虑具有查询参数的状态的这种情况.我想将它们声明为标志,这样我就可以在控制器中获取并获取true,false或者undefined
$stateProvider.state('foo.bar', {
url: '/foobar?flag1&flag2',
templateUrl: 'foo/bar/template.tpl.html',
controller: 'FooBarCtrl'
});
myModule.controller('FooBarCtrl', function($stateParams){
$stateParams.flag1 <<--- is string but can it be of type bool?
$stateParams.flag2 <<--- is string but can it be of type bool?
});
Run Code Online (Sandbox Code Playgroud)
一些URL示例:
/foobar?flag1=true -->> should yield {flag1: true, flag2: undefined}
/foobar?flag2=false -->> should yield {flag1: undefined, flag2: false}
/foobar?flag1=false&flag2=true -->> should yield {flag1: false, flag2: true}
/foobar?flag1=1&flag2=0 -->> should yield {flag1: true, flag2: false}
etc...
Run Code Online (Sandbox Code Playgroud)
目前$ stateParams只提供字符串.有没有让路由器解析params作为标志?这比在控制器中手动解析要优雅得多.
您应该能够将bool用作类型
url: '/foobar?{flag1:bool}&{flag2:bool}',
Run Code Online (Sandbox Code Playgroud)
但我们甚至可以使用我们的自定义类型(让我们称之为boolean):
app.config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) {
$urlMatcherFactory.type('boolean',
{
name : 'boolean',
decode: function(val) { return val == true ? true : val == "true" ? true : false },
encode: function(val) { return val ? 1 : 0; },
equals: function(a, b) { return this.is(a) && a === b; },
is: function(val) { return [true,false,0,1].indexOf(val) >= 0 },
pattern: /bool|true|0|1/
})
}]);
Run Code Online (Sandbox Code Playgroud)
url的状态def 将是这样的:
url: '/foobar?{flag1:boolean}&{flag2:boolean}',
Run Code Online (Sandbox Code Playgroud)
这应该工作:
<a ui-sref="foobar({ flag1: 0, flag2:true })">
<a ui-sref="foobar({ flag1: 1, flag2:false })">
Run Code Online (Sandbox Code Playgroud)
这里有一些例子
最终以下对我有用:
var stringToBoolean = function (s) {
if (typeof s != 'string') {
return undefined
}
if (/1|true|TRUE/.test(s)) {
return true
} else if (/0|false|FALSE/.test(s)) {
return false
} else {
return undefined
}
};
$stateProvider.state('foo.bar', {
url: '/foobar?{flag1}',
...
onEnter: function ($stateParams) {
$stateParams.flag1 = stringToBoolean($stateParams.flag1);
}
});
Run Code Online (Sandbox Code Playgroud)
它感觉不是超级干净,我宁愿将此功能集成到 ui-router 中,但至少我能够以这种方式在状态级别解决此问题,而不会用此逻辑污染我的控制器。
| 归档时间: |
|
| 查看次数: |
5134 次 |
| 最近记录: |