Last active
November 30, 2015 05:46
-
-
Save flyakite/0da33828f7b228118f35 to your computer and use it in GitHub Desktop.
service for $cordovaGoogleAnalytics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GA.startTrackerWithId('UA-70824422-1'); | |
GA.trackView('News'); | |
GA.addCustomDimension('Type', 'tips'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* The $cordovaGoogleAnalytics can't be used directly in controllers until analytics is available. | |
* So I package $cordovaGoogleAnalytics into a GA service. | |
* For every $cordovaGoogleAnalytics method, this service ensure the core analytics is available. | |
* The problem is I found I repeat myself a lot for every method. | |
* Is there a better implementation for this service?? | |
*/ | |
angular.module('app.services', []) | |
.factory('GA', function($q, $cordovaGoogleAnalytics) { | |
var service = { | |
_initCount: 0, | |
/** | |
* Initialize $cordovaGoogleAnalytics when analytics is available | |
* @return {Promise} | |
*/ | |
_init: function(){ | |
var d = $q.defer(); | |
if(typeof analytics !== 'undefined'){ | |
service._initCount = 0; | |
d.resolve(); | |
}else if(service._initCount > 50){ | |
d.reject(); | |
}else{ | |
service._initCount ++; | |
setTimeout(function(){ | |
d.resolve(service._init()); | |
},500); | |
} | |
return d.promise; | |
}, | |
startTrackerWithId: function(ID) { | |
var d = $q.defer(); | |
service._init().then(function() { | |
var r = $cordovaGoogleAnalytics.startTrackerWithId(ID); | |
d.resolve(r); | |
}); | |
return d.promise; | |
}, | |
setUserId: function(username) { | |
var d = $q.defer(); | |
service._init().then(function() { | |
d.resolve($cordovaGoogleAnalytics.setUserId(username)); | |
}); | |
return d.promise; | |
}, | |
trackView: function(name) { | |
var d = $q.defer(); | |
service._init().then(function() { | |
var r = $cordovaGoogleAnalytics.trackView(name); | |
d.resolve(r); | |
}); | |
return d.promise; | |
}, | |
addCustomDimension: function(field, value) { | |
var d = $q.defer(); | |
service._init().then(function() { | |
d.resolve($cordovaGoogleAnalytics.addCustomDimension(field, value)); | |
}); | |
return d.promise; | |
} | |
}; | |
return service; | |
}) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment