Search code examples
javascriptangularjsgoogle-analyticsangulartics

Using Angulartics and Google Analytics for Dynamic and Unique URLs


I am attempting to use angulartics and Google Analytics in my AngularJS SPA such that I will be able to aggregate pageviews even though the URLs constructed are unique when the user is in the app. As a user is moving from page to page (and state to state), the URL will continue to build upon itself including GUIDs. Please see below for an example:

  1. Page 1: localhost:9000/selectListing
  2. Page 2: localhost:9000/34ea85a0-84db-4443-b40b-f7e0b6b0b096/selectFiles
  3. Page 3: localhost:9000/34ea85a0-84db-4443-b40b-f7e0b6b0b096/addUser/ceb1639a-1ba4-4f09-a175-474bea0fe3bf

When I look at this information on google analytics, I see a unique URL for every time a user is on the selectFiles page under the list of realtime page views. For example:

  1. localhost:9000/34ea85a0-84db-4443-b40b-f7e0b6b0b096/selectFiles
  2. localhost:9000/0c006d26-bff4-43da-aaee-d332f92b05db/selectFiles

I would just like to see it aggregated so that there would be a user count on the /selectFiles page instead

Here is my google analytics code in my index.html file:

if (window.location.host.indexOf('cats.kittens.com') >=0){
        (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-5555555-5', 'auto');
        $window.ga('send', 'pageview', { page: $location.url() });

Here is the code I implemented in my app.js file:

angular.module('myApp', [
    'ui.router', 'ui.bootstrap', 'ui.bootstrap.tpls', 'ngTable', 'ngSanitize', 'angularFileUpload','angular.filter', 'angulartics', 'angulartics.google.analytics',
    ])
/* Angulartics configuration */
.config(['$analyticsProvider', function ($analyticsProvider) {
    $analyticsProvider.firstPageview(false); /* Records pages that don't use $state or $route */
    $analyticsProvider.withAutoBase(true);  /* Records full path */
}])
.config(['$stateProvider', '$urlRouterProvider', '$logProvider', function ($stateProvider, $urlRouterProvider, $logProvider) {
    'use strict';

    // global $log.debug setting
    $logProvider.debugEnabled(true);

}]);

I have tried this solution with google analytics and ui-router with no success: http://www.arnaldocapo.com/blog/post/google-analytics-and-angularjs-with-ui-router/72

Please let me know anything else I might be able to try. Thanks in advance!


Solution

  • After researching this issue for a couple more days on github I found a solution. I added this run block to my app.js file:

    .run(['$rootScope', '$stateParams', '$analytics', '$location', '$log', function($rootScope, $stateParams, $analytics, $location, $log) {
        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams) {
            var overrideStateParams = {};
            var flattener = null;
            if (toState.angulartics && toState.angulartics.flattenParams === true)
            {
                angular.forEach(toParams, function(v,k) {
                    overrideStateParams[k] = ':' + k;
                });
            }
            else if (toState.angulartics && angular.isArray(toState.angulartics.flattenParams))
            {
                angular.forEach(toState.angulartics.flattenParams, function(flattenParam) {
                    overrideStateParams[flattenParam] = ':' + flattenParam;
                });
            }
            else
            {
                // default is to not flatten
            }
            var url = location.host + decodeURIComponent(location.hash);
            url = url.replace(/#/, '/').replace(/\/+/g, '/').replace(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/ig, 'GUID');
            $log.info(url);
            $analytics.pageTrack(url);
        });
    }])
    

    Please note that I am replacing a GUID with the regex in my code above. You may need to change the regex to fit your needs for your unique URL. I also added this piece of code to each state in which I needed my URL truncated:

    angulartics: { flattenParams: true }
    

    You would implement it like this in your route config file by state:

                .state('Kittens.meow', {
                    url: '/meow',
                    templateUrl: 'meow/hiss.html',
                    angulartics: { flattenParams: true }
                })