Tracking Google Analytics Page Views with AngularJS

前端 未结 21 982
北恋
北恋 2020-11-27 09:14

I\'m setting up a new app using AngularJS as the frontend. Everything on the client side is done with HTML5 pushstate and I\'d like to be able to track my page views in Goog

21条回答
  •  没有蜡笔的小新
    2020-11-27 09:44

    In your index.html, copy and paste the ga snippet but remove the line ga('send', 'pageview');

    
    
    

    I like to give it it's own factory file my-google-analytics.js with self injection:

    angular.module('myApp')
      .factory('myGoogleAnalytics', [
        '$rootScope', '$window', '$location', 
        function ($rootScope, $window, $location) {
    
          var myGoogleAnalytics = {};
    
          /**
           * Set the page to the current location path
           * and then send a pageview to log path change.
           */
          myGoogleAnalytics.sendPageview = function() {
            if ($window.ga) {
              $window.ga('set', 'page', $location.path());
              $window.ga('send', 'pageview');
            }
          }
    
          // subscribe to events
          $rootScope.$on('$viewContentLoaded', myGoogleAnalytics.sendPageview);
    
          return myGoogleAnalytics;
        }
      ])
      .run([
        'myGoogleAnalytics', 
        function(myGoogleAnalytics) {
            // inject self
        }
      ]);
    

提交回复
热议问题