【问题标题】:$stateParams converting value to string$stateParams 将值转换为字符串
【发布时间】:2016-02-13 21:01:24
【问题描述】:

我正在使用UI-Router。这是我通过ui-sref 路由到的状态之一:

.state("community", {
    url: "/community/:community_id",
    controller: "CommunityCtrl",
    templateUrl: "/static/templates/community.html"
})

在我进入“社区”状态的模板之一中:

<div ui-sref="community({community_id: community.community_id})"></div>

这是我的社区对象:

{
    name: 'Community name',
    community_id: 11 //int, not a string
}

如您所见,键“community_id”包含一个 int 值而不是字符串值。但是,当我通过$stateParams 访问此参数时,我得到:

community_id: "11" //string

为什么我得到一个字符串?

【问题讨论】:

    标签: javascript angularjs angular-ui-router ui-sref


    【解决方案1】:

    获取 community_id 作为数字 (int) 的最简单方法是将参数声明为 int - {community_id:int}

    .state("community", {
        url: "/community/{community_id:int}",
        controller: "CommunityCtrl",
        templateUrl: "/static/templates/community.html"
    })
    

    查看有关.state() setting url的文档:

    带有可选参数的url 片段。当状态被导航或转换到时,$stateParams 服务将填充任何传递的参数。

    (有关可接受模式的更多详细信息,请参阅 UrlMatcher UrlMatcher})

    例子:

    url: "/home"
    url: "/users/:userid"
    url: "/books/{bookid:[a-zA-Z_-]}"
    url: "/books/{categoryid:int}"
    url: "/books/{publishername:string}/{categoryid:int}"
    url: "/messages?before&after"
    url: "/messages?{before:date}&{after:date}"
    url: "/messages/:mailboxid?{before:date}&{after:date}"
    

    【讨论】:

    • @RadimKöhler 一个问题,对于date 类型,我们需要指定格式吗?
    • @PankajParkar 希望你在这里得到答案:github.com/angular-ui/ui-router/blob/master/src/…
    • @RadimKöhler 我明白了..我需要考虑在我的应用程序中进行重构..非常感谢.. +1 感谢其他问题的帮助..
    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多