How to Use Google Analytics in AngularJS


It seems to be quite a popular question with not as many answers to hold the weight.

Google Analytics has always been more of a pageviews type tracking use case and up until a few years ago that was all anyone ever really did anyways. However,  the web has gotten a lot more complicated with the introduction of javascript and heavy ajax based sites and web applications.

This has caused quite a change in how Analytics Tools are used and how they are expected to gather statistics.

Luckily there are ways to achieve this and Arnaldo Capo has already written about it over at his blog (no longer active). We have included his code below for clarity as well as in case the site is down for some reason in the future.

So let?s get into the gory details.

Basically it’s all about setIntervals and dom listeners, or in AngularJS, state changes.

On the script provided by google remove the last line as shown in the following example.

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'yourdomain.com'); //ga('send', 'pageview');

Then in your app bootstrap, register a $rootScope event named $stateChangeSuccess. $stateChangeSuccess will fire every time a state changes. See code below.

angular.module('yourApp', []) .run(['$rootScope', '$location', '$window', function($rootScope, $location, $window){ $rootScope .$on('$stateChangeSuccess', function(event){ if (!$window.ga) return; $window.ga('send', 'pageview', { page: $location.path() }); }); }]);

If all this is just too much for you, then you might be quite pleased to learn that Statvoo takes the hassle away of tracking javascript sites by handling it all by itself with zero additional implementation required.