Google Analytics service is one of the most used tools concerning monitoring of web applications. In this article we are to discuss how to perform integration of sdk inside your applications and some suggestions to use it in the same way as you would do with a Server-side application.

So you need to get the first part of a configuration. 

.config(function myAppConfig(AnalyticsServiceProvider ) {

In this configuration you have to set the host and the GA apikey. For this purpose you need to use a Provider followed by a Factoryi, to be sure that GA is unique inside your application. 

function embedScript($document, success, error) {
            var el = angular.element('<script>').attr({

            el.onreadystatechange = el.onload = function () {


You are creating with this function a script tag to be included into the header, in the same way as the normal use of Google Analytics Snippet. 

this.$get = ['$document', '$timeout', '$q', '$rootScope', '$window',
            function ($document, $timeout, $q, $rootScope, $window) {
                var def = $q.defer();
                var ga;

                var initGa = function(){
                    $'create', analyticsId, host);

                var onScriptLoad = function () {
                    $timeout(function () {
                embedScript($document, onScriptLoad);
                return def.promise;

$get is the default function called when the Provider is used: so before invoking the script, you have to initialize it with your configuration.

The library loading is asynchronous. So you need to implement a Promise, to be sure that the following calls made by sdk are executed only after loading the Analytics library.  For the purpose you can use $q, a component made available by Angular itself.

Now you can use a Factory to implement some methods: one is needed for tracing the page display, another one has to return the whole GA object, to be used within your Angular application.

.factory('Analytics', ['AnalyticsService',
            return {
                pageView: function (path) {
                        ga('send','pageview', path);
                ga: function() {
                        return ga;

By implementing the Promises, you can use GA directly as it is certainly available.  


comments powered by Disqus


Follow Us