AngularJS: Right approach for using Google Analytics
Question
I am wondering which is the right way of integrating Google Analytic into my AngularJS app. I would like to provide it through DI, so I can mock it during unit testing, and test which data is being sent to it.
I was trying something like this:
.service('$ga', function () {
(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', 'GA_KEY', 'auto');
ga('send', 'pageview');
return ga;
})
But of course it does not work, since first is a dummy object and when analytics.js
loads, replaces window.qa
(ie:window[document['GoogleAnalyticsObject']]
) with the proper implementation. So when the service runs, returns the dummy implementation.
I guess that using a provider will be the right way, since I would like to also configure some parameters (like UserID, etc...), but I have no idea how to set it up that way.
Which is the right approach?
Solution
This is the best I got so far:
.provider('$ga', function () {
window['GoogleAnalyticsObject'] = 'ga';
window['ga'] = window['ga'] || function () { (window['ga'].q = window['ga'].q || []).push(arguments)}
window['ga'].l = 1 * new Date();
var script = document.createElement('script');
var prevScript = document.getElementsByTagName('script')[0];
script.async = 1;
script.src = '//www.google-analytics.com/analytics.js';
prevScript.parentNode.insertBefore(script, prevScript);
var provider = function () {
var me = {};
me.$get = function () {
ga('send', 'pageview');
return function () {
return window.ga.apply(window, arguments);
}
};
me.ga = function () {
return window.ga.apply(window, arguments);
};
return me;
};
return provider();
})
It is a provider that can be configured:
.config(['$gaProvider',function ($gaProvider) {
$gaProvider.ga('create','UA-XXXXXX-Y','auto');
}])
Feedback is welcomed.