Tracking Google Analytics Page Views with AngularJS

前端 未结 21 916
北恋
北恋 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:34

    When a new view is loaded in AngularJS, Google Analytics does not count it as a new page load. Fortunately there is a way to manually tell GA to log a url as a new pageview.

    _gaq.push(['_trackPageview', '']); would do the job, but how to bind that with AngularJS?

    Here is a service which you could use:

    (function(angular) { 
    
      angular.module('analytics', ['ng']).service('analytics', [
        '$rootScope', '$window', '$location', function($rootScope, $window, $location) {
          var track = function() {
            $window._gaq.push(['_trackPageview', $location.path()]);
          };
          $rootScope.$on('$viewContentLoaded', track);
        }
      ]);
    
    }(window.angular));
    

    When you define your angular module, include the analytics module like so:

    angular.module('myappname', ['analytics']);
    

    UPDATE:

    You should use the new Universal Google Analytics tracking code with:

    $window.ga('send', 'pageview', {page: $location.url()});
    

提交回复
热议问题