Tracking pageviews with Google Analytics and AngularJS

Angular JS Google Analytics

If you need to track the full url of your AngularJS application, here is a very simple code to do that.

The problem

My first approach to tracking page views in Google Analytics:

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

It works fine to track pages like "/register" and "/list-elements". However, if I want to track pages like "/list-elements?filter=name", Google Analytics saves "/list-elements" only.
The main problem is that $location.path() doesn't return URL parameters.

The solution

Luckily exists $routeParams, which saves URL parameters and provides the solution of our problem.

App.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 final result is:

/list-elements?filter=name