使用ui-router的"bool"param类型的正确方法是什么?

bra*_*hnp 11 angularjs angular-ui-router

我一直在尝试使用ui-router的param类型,似乎无法使它们正确.

$stateProvider.state({ name: 'home.foo', url: '/foo/{isBar:bool}', controller: function() { }, templateUrl: 'foo.html' });

我的期望是我应该能够像这样过渡到那个州:

$state.go(home.foo, { isBar: false })

要么

ui-sref="home.foo({ isBar: false })"

但是在结果$ stateParams中你会看到isBar:true

看一下' bool'param类型的编写方式,我认为true/false应该在url上编码为0/1,但这不会发生.如果在$ state.go的params中使用0/1然后它工作并被解码为false/true但是为了进一步混淆问题,如果使用ui-sref则这不起作用.

希望这个掠夺者会更好地解释它.任何提示赞赏!

编辑:我使用bool param类型的目的是在$ stateParams中以布尔数据类型结束

Rad*_*ler 11

有一个更新和工作的plunker与boolean自定义类型

在这种情况下,我们希望使用类似bool的类型,它期望并接受:

true,false,0,1

我们只需要注册我们的自定义类型:

app.config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) {

  $urlMatcherFactory.type('boolean',
    // our type custom type
    {
     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定义:

...
, url: '/foo/{isBar:boolean}'
...
Run Code Online (Sandbox Code Playgroud)

注意:为什么boolean?不是bool吗?因为我记得bool已经注册了0|1

检查它在这里

原版的

在这个更新的plunker中使用"字符串"的简单解决方案,

... // states definitions
, url: '/foo/{isBar:(?:bool|true|0|1)}'
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 1

因此,在深入研究多个文件后,我发现为什么最后两种方法 (0,1) 在 ui-sref 中不起作用。stateDirectives.js 第 106 行有这样的调用:newHref = $state.href(ref.state, params, options);

在使用 1 和 0 的情况下,这将返回 null。并且由于上面的调用后面是这样的:

 if (newHref === null) {
      nav = false;
      return false;
    }
Run Code Online (Sandbox Code Playgroud)

永远不会建立链接。现在,返回原因为null。state.href 调用 urlRouter.href。其中包含验证参数的调用。验证是这样的: result = result && (isOptional || !!param.type.is(val));

当您查看 bool ( is: function(val) { return val === true || val === false; }) 的 is 函数时,您会明白为什么会失败,因为 1 和 0 不等于 true 或 false。在我看来,它还应该检查 1 和 0(如果这就是它最终转换为的值),但至少现在您知道它为什么会这样做。