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 )

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  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 .

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

Bonus

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