Tracking Google Analytics Page Views with AngularJS

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

    If you're using ng-view in your Angular app you can listen for the $viewContentLoaded event and push a tracking event to Google Analytics.

    Assuming you've set up your tracking code in your main index.html file with a name of var _gaq and MyCtrl is what you've defined in the ng-controller directive.

    function MyCtrl($scope, $location, $window) {
      $scope.$on('$viewContentLoaded', function(event) {
        $window._gaq.push(['_trackPageView', $location.url()]);
      });
    }
    

    UPDATE: for new version of google-analytics use this one

    function MyCtrl($scope, $location, $window) {
      $scope.$on('$viewContentLoaded', function(event) {
        $window.ga('send', 'pageview', { page: $location.url() });
      });
    }
    

提交回复
热议问题