forked from arnaudbreton/angular-segmentio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-segmentio.js
61 lines (54 loc) · 2.81 KB
/
angular-segmentio.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
angular.module('segmentio', ['ng'])
.factory('segmentio', ['$rootScope', '$window', '$location', '$log',
function($rootScope, $window, $location, $log) {
var service = {};
$window.analytics = $window.analytics || [];
// Define a factory that generates wrapper methods to push arrays of
// arguments onto our `analytics` queue, where the first element of the arrays
// is always the name of the analytics.js method itself (eg. `track`).
var methodFactory = function(type) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
$log.debug('Call segmentio API with', type, args);
if ($window.analytics.initialized) {
$log.debug('Segmentio API initialized, calling API');
$window.analytics[type].apply($window.analytics, args);
} else {
$log.debug('Segmentio API not yet initialized, queueing call');
$window.analytics.push([type].concat(args));
}
};
};
// Loop through analytics.js' methods and generate a wrapper method for each.
var methods = ['identify', 'track', 'trackLink', 'trackForm', 'trackClick',
'trackSubmit', 'page', 'pageview', 'ab', 'alias', 'ready', 'group'
];
for (var i = 0; i < methods.length; i++) {
service[methods[i]] = methodFactory(methods[i]);
}
// Listening to $viewContentLoaded event to track pageview
$rootScope.$on('$viewContentLoaded', function() {
if (service.location != $location.path()) {
service.location = $location.path();
service.pageview(service.location);
}
});
/**
* @description
* Load Segment.io analytics script
* @param apiKey The key API to use
*/
service.load = function(apiKey) {
// Create an async script element for analytics.js.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = ('https:' === document.location.protocol ? 'https://' : 'http://') +
'd2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/' + apiKey + '/analytics.js';
// Find the first script element on the page and insert our script next to it.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
};
return service;
}
]);