diff --git a/README.md b/README.md index 3add957..9a9d882 100644 --- a/README.md +++ b/README.md @@ -4,18 +4,15 @@ follow these step: -- Set 'YOUR GOOGLE ACCOUNT' in googleanalyticis.js placeholder with your google account id - Add the service to your angular js app module: ``var app = angular.module('myapp', ['analytics']) { ... });`` +- Set your analytics code: -- Now just have analytics to be injected in your contorller. + ``app.constant('gaKey', 'UA-XXXXXXXX-Y');`` - ``function myCtrl($rootScope, $scope, $http, analytics) { - ... - };`` Code licensed under The MIT License. diff --git a/analyticsService.js b/analyticsService.js index a787d2e..d2f5d93 100644 --- a/analyticsService.js +++ b/analyticsService.js @@ -1,34 +1,34 @@ -var _gaq = _gaq || []; +(function (){ -angular.module('analytics', []).run(['$http', function($http) { + var analytics = angular.module('analytics', []); - _gaq.push(['_setAccount', 'YOUR GOOGLE ACCOUNT']); - _gaq.push(['_trackPageview']); + analytics.constant( 'gaKey', 'XXXXXX-XX' ); - 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); + analytics.run(['$window','$location','$rootScope','gaKey', function($window, $location, $rootScope, gaKey) { -}]).service('analytics', function($rootScope, $window, $location, $routeParams) { + (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ + (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), + m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) + })($window,$window.document,'script','//www.google-analytics.com/analytics.js','ga'); - $rootScope.$on('$viewContentLoaded', track); + $window.ga('create', gaKey); - 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 track = function() { + $window.ga('send', 'pageview', { + location: $location.absUrl(), + page : $location.url() + }); + }; - var querystring = decodeURIComponent($.param($routeParams)); + $rootScope.$on('$viewContentLoaded', track); + }]); - if (querystring === '') return path; + analytics.service('analytics', ['$window',function($window) { + return { + trackEvent: function(action, label, value) { + $window.ga('send', 'event', action, label, value); + } + }; - return path + "?" + querystring; - }; -}); + }]); +})();