dj2 dj2 - 6 months ago 33
AngularJS Question

Tracking Google Analytics Page Views with Angular.js

I'm setting up a new app using Angular.JS as the frontend. Everything on the client side is done with HTML5 pushstate and I'd like to be able to track my page views in Google Analytics.

dj2 dj2
Answer

If you're using ng-view in your Angular app you can listen for the $viewContentLoaded event and push a tracking event to Google Analytics.

Assuming you've setup your tracking code in your main index.html file with a name of var _gaq and MyCtrl is what you've defined in the ng-controller directive.

function MyCtrl($scope, $location, $window) {
  $scope.$on('$viewContentLoaded', function(event) {
    $window._gaq.push(['_trackPageview', $location.url()]);
  });
}

UPDATE: for new version of google-analytics use this one

$window.ga('send', 'pageview', { page: $location.url() });
Comments