$stateParams将值转换为字符串

$stateParams converting value to string

本文关键字:字符串 转换 stateParams      更新时间:2023-09-26

我正在使用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

为什么我会被绳子缠住?

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

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

检查有关.state()设置的文档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}"