AngularJS and Google Analytics

Viewed 3411

I am trying to dynamically change my GA tracking ID (UA-XXXXXXX-X) depending on which environment the page is being viewed on but I can't seem to find a truly "angular" way to do it. I am using Angulartics but I can't get the base GA code to run which is needed before Angulartics can do anything. If I just put the GA code at the bottom of the page it works as expected but that isn't very Angular like and it still does not allow me to dynamically set the GA ID.

I have tried creating a directive but the tracking code doesn't seem to be run when put inside a directive's controller. I have created a controller that gets the environment from a rest call and then assigns a GA code based on the environment returned but when I run the directive it runs to early and the GA code doesn't fire or it fires while the tracking ID is still undefined. I also tried putting the GA code into the directives template but for some reason the code doesn't fire at all when placed inside script tags inside the ngAnalytics.html template even though i can see it is being correctly added to the page once the dom is loaded. I am new to angular so I know there is a solution but I am not seeing it. My directive is below:

angular.module('ngAnalytics', [])
.directive('ngAnalytics', function( servicesSrvc) {
    return {
        restrict: 'A',
        templateUrl: 'js/directives/ngAnalytics.html',
        controller: ['$scope', function($scope) {
            $scope.trackingID;
            $scope.getEnvDetails = function() {
                var currentEnv = servicesSrvc.getEnv();
                var env;
                currentEnv.then(function(data) {
                    env = JSON.stringify(data.environment);
                    switch(env)
                {
                    case 'local':
                        $scope.trackingID = 'disabled'; // DEV
                        break;
                    case 'dev':
                        $scope.trackingID = 'UA-XXX-X'; // DEV
                        break;
                    ...
                        $scope.trackingID = 'UA-XXX-X'; // Default to dev
                }
                (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', $scope.trackingID, { 'cookieDomain': 'none' }); // For localhost testing
                //ga('create', $scope.trackingID, 'test.com'); // For dev, qa, prod etc...
                //ga('send', 'pageview'); // MUST BE DISABLED when using Angulartics
            });
        }

    }],
    link: function(scope, iElement, iAttrs, ctrl) {

    }
}
});
1 Answers
Related