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.

(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'); <- 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){
     $rootScope
        .$on('$stateChangeSuccess',
            function(event){

                if (!$window.ga)
                    return;

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

Ta-da! Now back to the zone.