Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thalesfsp/4a504d9183a8714c35ea to your computer and use it in GitHub Desktop.
Save thalesfsp/4a504d9183a8714c35ea to your computer and use it in GitHub Desktop.
Google Analytics Page Views with Angular
(function(angular) {
angular.module('analytics', ['ng']).service('analytics', [
'$rootScope', '$window', '$location', function($rootScope, $window, $location) {
var track = function() {
$window._gaq.push(['_trackPageview', $location.path()]);
};
$rootScope.$on('$viewContentLoaded', track);
}
]);
}(window.angular));
angular.module('myappname', ['analytics']);
var _gaq = _gaq || [];
angular.module('analytics', []).run(['$http', function($http) {
_gaq.push(['_setAccount', 'YOUR GOOGLE ACCOUNT']);
_gaq.push(['_trackPageview']);
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
}]).service('analytics', function($rootScope, $window, $location, $routeParams) {
$rootScope.$on('$viewContentLoaded', track);
var track = function() {
var path = convertPathToQueryString($location.path(), $routeParams)
$window._gaq.push(['_trackPageview', path]);
};
var convertPathToQueryString = function(path, $routeParams) {
for (var key in $routeParams) {
var queryParam = '/' + $routeParams[key];
path = path.replace(queryParam, '');
}
var querystring = decodeURIComponent($.param($routeParams));
if (querystring === '') return path;
return path + "?" + querystring;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment