$ stateParams将值转换为字符串

Tar*_*gar 6 javascript angularjs angular-ui-router ui-sref

我在用UI-Router.这是我通过ui-sref以下路线选择的州之一:

.state("community", {
    url: "/community/:community_id",
    controller: "CommunityCtrl",
    templateUrl: "/static/templates/community.html"
})
Run Code Online (Sandbox Code Playgroud)

在我进入"社区"状态的一个模板中:

<div ui-sref="community({community_id: community.community_id})"></div>
Run Code Online (Sandbox Code Playgroud)

这是我的社区对象:

{
    name: 'Community name',
    community_id: 11 //int, not a string
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,关键字'community_id'包含一个int值而不是字符串值.但是,当我通过以下方式访问此参数时$stateParams:

community_id: "11" //string
Run Code Online (Sandbox Code Playgroud)

我为什么要收到一个字符串?

Rad*_*ler 11

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

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

检查有关.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}"
Run Code Online (Sandbox Code Playgroud)