Skip to content

Google Analytics and Angular UI Router

Tracker service:

(function () {
  'use strict';

  angular
    .module('app.core')
    .service('googleAnalyticsTracker', googleAnalyticsTracker);

  googleAnalyticsTracker.$inject = ['$state', '$window'];

  function googleAnalyticsTracker($state, $window) {

    /* jshint validthis: true */
    this.trackState = trackState;

    ////////////////

    function trackState() {
      var stateName = $state.current.name;
      var path = stateName.replace(/\./g, '/'); // replaces dots to mimic regular path with slashes
      $window.ga('set', 'page', path);
      $window.ga('send', 'pageview');
    }

  }

})();

Used whenever the state is changed:

  $rootScope.$on('$stateChangeSuccess', googleAnalyticsTracker.trackState);

Adapted rom: