Google Analytics with AngularJS and UI-Router

2015-07-29 12:54:59 -0400

I helped Clean Slate DC add Google Analytics to their app last night at Code For DC and realized others might not know how to do this. It's pretty simple, but you won't want to follow the directions on Google Analytics exactly. Instead, add this to your index.html or main page <head>, replacing your UA code with the UA code that Google gives you:

<!-- Google Analytics -->
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
ga('create', 'UA-XXXX-X', 'auto');
<!-- End Google Analytics -->

Next, add a service to your Angular project:

angular.module("app").service('Analytics', function() {

  this.recordPageview = function(url) {
    ga('set', 'page', url);
    ga('send', 'pageview');


Finally, add a run block near where your app starts:

angular.module("app").run(function($rootScope, $location, Analytics) {
  $rootScope.$on('$stateChangeSuccess', function() {

There you go!