AngularJS UI-Router:带参数获取状态的绝对 URL状态、参数、UI、AngularJS

2023-09-06 14:41:12 作者:余音未散

我希望能够在不更改状态的情况下更改地址的 URL,以防止重新呈现.根据我的搜索, ui-router 当前不提供此功能,但来自 anuglar 的 $location.path 提供.

I wanted to be able to change the address' URL without changing the state, as to prevent rerendering. From my search, ui-router currently does not provide this, but $location.path from anuglar does.

所以,很自然地,我想使用 $state.get(stateName) 来获取州的 URL,这样我就不用手动输入 URL.

So, naturally, I wanted to use $state.get(stateName) to get to the state's URL, so that I don't manually type the URL.

我有两个问题:

$state.get(stateName) 仅返回相对路径.如何获取绝对路径?它还返回状态的定义,参数未定义.如何获取带参数的 URL? $state.get(stateName) returns the relative path only. How can I get the absolute path? It also returns the state's definition, with the parameters undefined. How can I get the URL with the parameter in place?

例如,如果我有一个名为 user.home.viewuser.home 的状态,我将状态定义为

For instance, if I have a state called user.home.view with user.home, I have my states defined as

'user': {
     abstract: true,
     url: '^/users/'
},
'user.home': {
     url: ''
},
'user.home.view': {
     url: ':id/'
}

所以现在,$state.get(user.home.view).url 返回 :id/.如何获取完整的 URL(即 /users/5/)?

So right now, $state.get(user.home.view).url returns :id/. How can I get the full URL (i.e., /users/5/)?

推荐答案

你应该使用 $state.href().

要获取绝对 URL,您可以使用:

To get the absolute URL you can then use:

$state.href('user.home.view', {}, {absolute: true});

要获取带有参数的 URL,您需要将它们添加为第二个参数

To get the URL with the parameters in place you need to add them as the second argument