forked from arnaudbreton/angular-segmentio
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathangular-segmentio.js
65 lines (56 loc) · 2.69 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
62
63
64
65
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(method) {
return function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(method);
$window.analytics.push(args);
return $window.analytics;
};
};
// Loop through analytics.js' methods and generate a wrapper method for each.
var methods = ['identify', 'group', 'track', 'page', 'pageview', 'alias',
'ready', 'on', 'once', 'off', 'trackLink', 'trackForm', 'trackClick',
'trackSubmit'
];
for (var i = 0; i < methods.length; i++) {
service[methods[i]] = methodFactory(methods[i]);
}
/**
* @description
* Load Segment.io analytics script
* @param apiKey The key API to use
*/
service.load = function(key) {
if (document.getElementById('analytics-js')) return;
// Create an async script element based on your key.
var script = document.createElement('script');
script.type = 'text/javascript';
script.id = 'analytics-js';
script.async = true;
script.src = ('https:' === document.location.protocol
? 'https://' : 'http://')
+ 'cdn.segment.io/analytics.js/v1/'
+ key + '/analytics.min.js';
// Insert our script next to the first script element.
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(script, first);
};
// Add a version to keep track of what's in the wild.
$window.analytics.SNIPPET_VERSION = '1.3.29';
// Listening to $viewContentLoaded event to track pageview
$rootScope.$on('$viewContentLoaded', function() {
if (service.location != $location.path()) {
service.location = $location.path();
service.page(service.location);
}
});
return service;
}
]);