-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogleAbTesting.js
98 lines (91 loc) · 2.51 KB
/
googleAbTesting.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
(function() {
'use strict';
angular.module('googleAbTesting', [])
.constant('GOOGLE_EXPERIMENTS', {
baseUrl: '//www.google-analytics.com/cx/api.js?experiment=',
timeout: 300,
maxTries: 8
})
.provider('googleAbTesting', ['GOOGLE_EXPERIMENTS',
function GoogleAbTestingProvider(GOOGLE_EXPERIMENTS) {
var _experimentId = null,
tries = 0,
_setExperimentId,
_getExperimentId,
scriptAdded = false;
this.setExperimentId = _setExperimentId = function(experimentId) {
_experimentId = experimentId;
};
this.getExperimentId = _getExperimentId = function() {
return _experimentId;
};
var _appendScript = function(experimentId) {
if (scriptAdded) {
return;
}
scriptAdded = true;
var s = document.createElement('script');
s.src = GOOGLE_EXPERIMENTS.baseUrl + experimentId;
document.body.appendChild(s);
};
var deferred;
var _getVariation = function($q, $interval) {
if (!deferred) {
deferred = $q.defer();
}
if (!this.getExperimentId()) {
deferred.reject('Google Experiment ID not set');
return deferred.promise;
}
_appendScript(this.getExperimentId());
var to = $interval(function loadGoogleApi() {
if (typeof cxApi !== 'undefined') {
deferred.resolve(cxApi.chooseVariation());
$interval.cancel(to);
return;
}
if (++tries > GOOGLE_EXPERIMENTS.maxTries) {
deferred.reject('cxApi not loaded within ' +
GOOGLE_EXPERIMENTS.maxTries + ' tries');
$interval.cancel(to);
return;
}
});
return deferred.promise;
};
this.$get = ['$q', '$interval', function($q, $interval) {
return {
setExperimentId: _setExperimentId,
getExperimentId: _getExperimentId,
getVariation: function() {
return _getVariation.call(this, $q, $interval);
}
};
}];
}])
.directive('variation', ['$log', 'googleAbTesting', function($log, googleAbTesting) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.addClass('ng-cloak');
function toggleElement(visible) {
if (visible) {
element.removeClass('ng-cloak');
element.removeClass('ng-hide');
} else {
element.addClass('ng-hide');
}
}
scope.$watch(attrs.variation, function(value) {
googleAbTesting.getVariation().then(function(variation) {
toggleElement(variation == parseInt(value));
return variation;
}).catch(function(err) {
// Default to variation 0 if no experiment found
toggleElement(parseInt(value) === 0);
});
});
}
};
}]);
})();