Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ui-router getting current path on state change for google analytics

I am trying to get the path of the state to send to google analytics. There are some issues. I am using abstract states, so using something like toState.url wont work as it wont grab the entire url.

I thought of using $window.location.pathname on $stateChangeSuccess, but it turns out success fires before the url is updated in the browser. This means that pageviews get sent 1 page view too late. ie.

click about: sends nothing
click contact: sends about url
click services: sends contact url

Basically the end result should look something like this, but with the toState url or pathname:

$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
  var path = ???; 
  ga('send', 'pageview', path);
});
like image 672
codephobia Avatar asked Sep 30 '22 05:09

codephobia


1 Answers

looks like you need to use $location instead to get the new path:

$rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams) {
  $window.ga('send', 'pageview', $location.path());
});
like image 80
codephobia Avatar answered Oct 04 '22 04:10

codephobia