本文介绍了$stateParams 将值转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using UI-Router. Here's one of my state to which I am routing via ui-sref:

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

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

In one of my templates from where I go to 'community' state:

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

这是我的社区对象:

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

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

As you can see the key 'community_id' contains an int value rather than string value. However, when I access this parameter via $stateParams I get:

community_id: "11" //string

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

Why am I getting a string?

推荐答案

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

The easiest way to get community_id as number (int) is to declare that param as int - {community_id:int}

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

查看关于.state() 设置url:

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

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

(See UrlMatcher UrlMatcher} for more details on acceptable patterns )

示例:

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}"

这篇关于$stateParams 将值转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:45