Published: November 07 2015

AngularJS - Google Analytics with the UI Router

This is a quick post to show how to setup Google Analytics page/route tracking in an Angular application that uses the UI Router. The code from the example is taken from a small website I built recently for a computer repair service in Campbelltown, Sydney. You can see the code in action at Snoopex Computer Repairs Campbelltown & Wollongong


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', ...).

<script>
    (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');
</script>


Initialise Google Analytics in the app run function

In your angular app's run function include the following line to initialise the Google analytics script:

$window.ga('create', 'UA-XXXXXXXX-X', 'auto');


Trigger pageview on ui-router $stateChangeSuccess event

Just below the above line, subscribe to the '$stateChangeSuccess' event of the UI Router and send a pageview with the current $location.path() to google analytics:

$rootScope.$on('$stateChangeSuccess', function (event) {
    $window.ga('send', 'pageview', $location.path());
});

 

Angular app.js file

Here is a cut down version of the app.js file including the config and run functions so you can see how it all ties together. To see the actual working code check out the Snoopex Computers Campbelltown website at http://www.snoopex.com.au.

(function () {
    'use strict';

    angular
        .module('app', ['ui.router'])
        .config(config)
        .run(run);

    config.$inject = ['$locationProvider', '$stateProvider', '$urlRouterProvider'];
    function config($locationProvider, $stateProvider, $urlRouterProvider) {
        $locationProvider.html5Mode(true);

        $urlRouterProvider.otherwise("/");

        $stateProvider

            .state('home', {
                url: '/',
                templateUrl: 'views/home.html',
                controller: function ($rootScope) {
                    $rootScope.title = 'Snoopex Computer Repairs and Upgrades Campbelltown and Wollongong';
                    $rootScope.metaDescription = 'Professional computer repairs, upgrades and custom built PCs. Providing professional computer repair services to the Campbelltown and Wollongong areas for over 20 years.';
                }
            })

        // ... other routes excluded for brevity

        ;
    }

    run.$inject = ['$rootScope', '$location', '$window'];
    function run($rootScope, $location, $window) {
        // initialise google analytics
        $window.ga('create', 'UA-XXXXXXXX-X', 'auto');

        // track pageview on state change
        $rootScope.$on('$stateChangeSuccess', function (event) {
            $window.ga('send', 'pageview', $location.path());
        });
    }
})();

 


Need Some AngularJS Help?

Search fiverr for freelance AngularJS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by