AngularJS UI-Router : Get the absolute URL of the state with the parameters

AngularjsAngular Ui-Router

Angularjs Problem Overview


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.

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.

I have two problems:

  1. $state.get(stateName) returns the relative path only. How can I get the absolute path?
  2. It also returns the state's definition, with the parameters undefined. How can I get the URL with the parameter in place?

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/'
}

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

Angularjs Solutions


Solution 1 - Angularjs

You should use $state.href().

  1. To get the absolute URL you can then use:

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

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

Solution 2 - Angularjs

What about :

$state.href($state.current.name, $state.params, {absolute: true})

Solution 3 - Angularjs

For getting the absolute URL without parameters, I'm finding I need to pass inherit: false, eg:

$state.href('home', {}, {absolute: true, inherit: false})

Without inherit: false I was getting any/all params that may be present.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKoushaView Question on Stackoverflow
Solution 1 - AngularjsadamKView Answer on Stackoverflow
Solution 2 - AngularjsJean F.View Answer on Stackoverflow
Solution 3 - AngularjsIsaac GregsonView Answer on Stackoverflow