Tracking Google Analytics Page Views with AngularJS

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

    Merging the answers by wynnwu and dpineda was what worked for me.

    angular.module('app', [])
      .run(['$rootScope', '$location', '$window',
        function($rootScope, $location, $window) {
          $rootScope.$on('$routeChangeSuccess',
            function(event) {
              if (!$window.ga) {
                return;
              }
              $window.ga('send', 'pageview', {
                page: $location.path()
              });
            });
        }
      ]);
    

    Setting the third parameter as an object (instead of just $location.path()) and using $routeChangeSuccess instead of $stateChangeSuccess did the trick.

    Hope this helps.

提交回复
热议问题