Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Tracking Pageviews with Google Analytics and Angular JS

Recently I noticed in my Google analytics dashboard that Analytics wasn’t tracking the full url of the page of my Angular JS site. I was tracking individual pageviews using this code in my app.js file:

MyApp.run(function($rootScope, $location, $window){
    $rootScope.$on('$routeChangeSuccess', function() {
        $window._gaq.push(['_trackPageview', $location.path()]);

I was receiving pageview counts just fine, but it was leaving off URL parameters. I was getting:


Which is ok, but instead I would like to see:


Needless to say this was an ideal situation, I didn’t know what users were searching for. Turns out, Angular’s $location.path() function does not return URL parameters. Luckily I found $routeParams.

$routeParams, part of ngRoute, is basically a keystore of URL parameters. A quick console.log($routeParams) in the console shows:

Object {searchTerm: "search"}

Using Angular’s awesome dependency injection, the ending product is easy. Inject $routeParams, build a query string, attach to $location.path(), and push to _gaq:

MyApp.run(function($rootScope, $location, $routeParams, $window){
    $rootScope.$on('$routeChangeSuccess', function() {
        var output=$location.path()+"?";
        $window._gaq.push(['_trackPageView', output]);

The ending result gives me this entry in Google Analytics:

Chris Mitchell

Chris Mitchell

Web developer from Modesto California. Working at UC Merced. jQuery, PHP/Zend, you rock. I rock on guitar sometimes too ;)


Follow Us

The Polyglot Developer


Subscribe to the newsletter for monthly tips and tricks on subjects such as mobile, web, and game development.

The Polyglot Developer

Support This Site