author thumb

Software Developer

Using google analytics on AngularJS

Google analytics is a essencial tool for tracking your website visits and understand a little bit more about your customer. In this post i’ll show you how to configure Google analytics in any AngularJS app, and how to track any event in a very simple and effective way.

First of all, you need to include your google analytics code ( You can put this code right before close your body tag )

  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  ga('create', 'UA-XXXXXXX-X', 'YOURWEBSITE.COM');
  ga('send', 'pageview');

Change the UA-XXXXXXX-X code for the ID that google gave you.

Now its very simple, lets create a $on. event on our main controller to tracking every page change .

  .controller('MainCtrl', function ($scope, $window, $location, $routeParams) {
    $scope.$on('$viewContentLoaded', function(event){
      // Tracking current page
      ga('send', 'pageview', {'page': $location.path()});


To track a custom event you need to do something like this:

< img ng-click="track(myimagesrc)" ng-src="">
$scope.track = function(image_src){
  ga('send', 'event', 'image', 'click', image_src);
author thumb

Hugo Dias

Desenvolvedor Back-end & Front-end, Desenvolvimento Android e IOS, HTML5, CSS3 e JavaScript