forked from troex/angular-segmentio
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathng-segmentio.js
78 lines (65 loc) · 2.53 KB
/
ng-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
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict'
window.angular.module('segmentio', ['ng']).factory(
'segmentio',
['$rootScope', '$window', '$location', '$q',
function ($rootScope, $window, $location, $q) {
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', 'reset'
]
for (var i = 0; i < methods.length; i++) {
service[methods[i]] = methodFactory(methods[i])
}
/**
* @description
* Load Segment.io analytics script
* @param key The key API to use
*/
service.load = function (key) {
var deferred = $q.defer()
if (document.getElementById('analytics-js')) {
deferred.resolve($window.analytics)
} else {
// 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 = (document.location.protocol === 'http:'
? 'http:' : 'https:')
+ '//cdn.segment.io/analytics.js/v1/'
+ key + '/analytics.min.js'
script.onload = script.onreadystatechange = function () {
deferred.resolve($window.analytics)
}
// Insert our script next to the first script element.
var first = document.getElementsByTagName('script')[0]
first.parentNode.insertBefore(script, first)
}
return deferred.promise
}
// Add a version to keep track of what's in the wild.
$window.analytics.SNIPPET_VERSION = '3.0.1'
// Listening to $viewContentLoaded event to track pageview
$rootScope.$watch(function () {
return $location.path()
}, function (value) {
service.page(value)
})
return service
}])