Ganesh Matkam Ganesh Matkam - 2 months ago 12
AngularJS Question

toState.url value is not an absolute hash for nested states

I'm trying to get

url
of
toState
object in
$stateChangeStart
event for a state
basic.tasks
:

$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
...
console.log(toState.name); // > basic.tasks
console.log(toState.url); // > /tasks
...
}


State Config:

$stateProviderRef
.state('basic',{
url: '/b',
template: require('source/basic/templates/basic.html'),
controller: 'BasicController',
abstract: true
})
.state('basic.tasks', {
url: '/tasks',
template: require('source/basic/templates/tasks/tasks.html'),
controller: 'TasksController',
})


The value of toState.url is
/tasks
instead of
/b/tasks
. Is there any way to get full hash including parent states.

I tried with
$window.location.hash
, but its giving only full hash path of
fromState
since it doesn't update until state change completes.

Answer

There's no simple way to do this unless you just add the parent state to the url, but if you're looking for a more dynamic way then this could be one option. I'm not sure if you have the hashtag in your url (usually it is there and in this we use it just for the regexp to remove the hashtag - but it looks something like this http://localhost:8100/#/app in localhost) but if you do, you could try something like this:

$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
  var href = $state.href(toState.name);
  var regexp = new RegExp('#','g');
  href = href.replace(regexp, '');
  console.log(href);
});

If you have parameters in your url for some state you can add them to the absolute url with toParams since the parameters do not get added to the url with this function on stateChangeStart. It would work directly on stateChangeSuccess.

EDIT:

As Ganesh Matkam said in the comment section there actually is an easy solution for including stateParams to the url. It's as simple as:

$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
  var href = $state.href(toState.name, toParams);
  var regexp = new RegExp('#','g');
  href = href.replace(regexp, '');
  console.log(href);
});