Forked from huanglong-zz/Google Analytics Page Views with Angular.js
Created
October 16, 2014 18:02
-
-
Save thalesfsp/4a504d9183a8714c35ea to your computer and use it in GitHub Desktop.
Google Analytics Page Views with Angular
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
(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