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:

/search-results

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

/search-results?searchTerm=term

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()+"?";
        angular.forEach($routeParams,function(value,key){
            output+=key+"="+value+"&";
        })
        output=output.substr(0,output.length-1);
        $window._gaq.push(['_trackPageView', output]);
    });
})

The ending result gives me this entry in Google Analytics:

/search-results?searchTerm=search
Chris Mitchell

Chris Mitchell

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

Close

Subscribe To Our Newsletter

Stay up to date on the latest in web, mobile, and game development, plus receive exclusive content by subscribing to The Polyglot Developer newsletter.

Unsubscribe at any time without hassle.