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-resultsWhich is ok, but instead I would like to see:
/search-results?searchTerm=termNeedless 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
Web developer from Modesto California. Working at UC Merced. jQuery, PHP/Zend, you rock. I rock on guitar sometimes too ;)
Search
Recent Posts
- Building a REST API With Express Framework and MongoDB
- Build a Real-Time Voice Interview Coach with TypeScript and LiveKit
- Introducing CFP Manager to Manage Speaking Engagements for the Team
- Using Dot Notation to Query Nested Fields in MongoDB
- Build a Movie Watchlist with Node.js, TypeScript, and MongoDB