Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js and Google Analytics Content Experiment

So I'm trying to implement google analytics content experiment on a website which is made as angular one page website.

I had setup two versions of my home page, as / and /?v=2, pasted in the google code as instructed, at the very top of the <head> tag and it worked just fine, google sent 30% of traffic to one and 70% of traffic to the second version of the page.

The problem came when I tried to access say /contact, google would apparently think I'm still accessing / and would send me to /v=2(if I was the part of the 30% that is).

I'm not even sure why does it happen, but it does, I'm thinking what could help is if google's functions ran not right after load, but only after main page's angular controller would load.. But I could get the google code working in the said controller..

Has anyone dealt with this problem before?

like image 228
fxck Avatar asked Nov 20 '13 11:11

fxck


People also ask

How does Google Analytics integrate with Angularjs?

Include the Google Analytics script in your Angular App This should go in the head of your root page (usually index. html) just before the closing </head> tag, it adds the 'ga' object to the window object and dynamically loads the base google analytics script without the call to ga('create', ...).


2 Answers

What you can do is use API instead https://developers.google.com/analytics/devguides/collection/gajs/experiments#cxjs

Then all you have to do is to do something like this in your route/state definition

{
   templateUrl: function() {
      if(cxApi.chooseVariation() == 0) {
         return "version1.html";
      } else {
         return "version2.html";
      }

   }
}
like image 161
fxck Avatar answered Sep 18 '22 20:09

fxck


Using AngularJS you will be choosing and providing the variations within your Angular code. Google calls this browser-implementation only. So you do not use the standard experiment code snippet provided by the Google Analytics Web Interface. Instead you will be using the Content Experiment JavaScript API. So the script you'll be loading is:

<script src="//www.google-analytics.com/cx/api.js?experiment=EXPERIMENT_ID"></script>

If you're using ui-router:

As foxx already wrote you simply have to determine the variation by calling cxApi.chooseVariation() every time the user is exposed to the $state which you want to run the test on. You can either choose different templates in the $stateProvider.state() call (as shown by foxx) or you can simply resolve the variation number and inject it into the controller, to use variation classes in the template: ng-class="{original: isVariation(0), variation-one: isVariation(1)}"

Google provides a great guide to implement experiments on the client-side.

like image 27
Tob Avatar answered Sep 19 '22 20:09

Tob