Arnaldo Capo

Google Analytics and AngularJS with UI Router

If you are using Angular JS with UI Router, you will probably want to capture each state in the user flow. This code is only for the new Google Analytics tagging object (ga). The basic overview is the following:

–  Add your google snippet to the main state. Assuming is index.html.
–  Stop google analytics from firing on the first load.
–  Add an event on each state change provided by the ui router module.

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

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

ga('create', 'UA-XXXXXXXX-X', '');
//ga('send', 'pageview'); <- Comment this line.

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){

                if (!$

                $'send', 'pageview', { page: $location.path() });

Ta-da! Now back to the zone.