Dave
Dave

Reputation: 1216

UI Router State Change Tracking in Google Analytics

I have an AngularJS app that uses UI router. There are frequent state changes, though the location path almost always stays as root ('/'). I would like to track state changes in Google Analytics, employing all of the functionality that you can use with page views. The standard approach is to send a pageview event when a state change occurs as seen here:

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

The problem is that for most interactions, the $location.path() for my app will be '/'. The URL rarely changes. I'm new to the non-developer side of Google Analytics and am worried that this is going to make reporting less robust than it otherwise could be.

As far as I can tell my options are:

Could somebody with experience in this situation advise me on the proper way to move forward?

EDIT

Taking advice from the accepted answer, I ended up creating a service with the two following functions (among others)

var convertPageName = function(path,stateName){
    var ret = path;

    if(stateName) {
        ret = ret + ':' + stateName.replace(/\./g, '/');
    }

    return ret;

  };

  var callPageView = function(stateName) {
    var payload;

    if(undefined !== stateName) {
        payload = {page:convertPageName($location.path(),stateName), title: stateName};
    }
    else {
        payload = {page: $location.path};
    }

    $window.ga('set', payload);
    $window.ga('send', 'pageview');
  };

Upvotes: 2

Views: 2938

Answers (1)

mikeswright49
mikeswright49

Reputation: 3416

In the past what I've done is treat changes like state or route changes as "Page" views. The reason behind it is we can then track and play in the google analytics world more effectively. This is because GA was originally built around page based components. What you want to do is actually bind using ga.set and then push your page view or what ever events are being sent. By doing this you can now keep everything associated in GA. This makes your code as follows:

$rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams) {
    $window.ga('set',{page:$location.path() + toState.name.replace(/\./g, '/'), title:toState.name});
    $window.ga('send', 'pageview');
    //any other events to send. They're now all going to be associated 
    //with this state until there is another navigation
});

Upvotes: 5

Related Questions