我正在使用AngularJS作为前端设置一个新的应用程序。客户端上的一切都是用HTML5推送状态完成的,我希望能够在谷歌分析中跟踪我的页面视图。


当前回答

把wynnwu和dpineda的答案结合起来对我来说很有用。

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()
          });
        });
    }
  ]);

将第三个参数设置为一个对象(而不仅仅是$location.path()),并使用$routeChangeSuccess而不是$stateChangeSuccess就可以了。

希望这能有所帮助。

其他回答

如果你在Angular应用中使用ng-view,你可以监听$viewContentLoaded事件,并将跟踪事件推送到谷歌Analytics。

假设你已经在主index.html文件中设置了跟踪代码,名称为var _gaq, MyCtrl是你在ng-controller指令中定义的。

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

更新: 新版本的谷歌分析使用这个

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

当AngularJS中加载一个新视图时,谷歌Analytics不会将其计算为新页面加载。幸运的是,有一种方法手动告诉GA日志url作为一个新的页面视图。

_gaq。push ([' _trackPageview ', ' < url > ']);可以完成这项工作,但是如何将它与AngularJS绑定呢?

这里有一个你可以使用的服务:

(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));

当你定义你的angular模块时,像这样包含analytics模块:

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

更新:

您应该使用新的通用谷歌分析跟踪代码:

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

对于那些使用AngularUI路由器而不是ngRoute的人来说,可以使用下面的代码来跟踪页面视图。

app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        ga('set', 'page', toState.url);
        ga('send', 'pageview');
    });
});

如果有人想实现using指令,那么就在index.html中标识(或创建)一个div(就在body标签下面,或在相同的DOM级别)。

<div class="google-analytics"/>

然后在指令中添加如下代码

myApp.directive('googleAnalytics', function ( $location, $window ) {
  return {
    scope: true,
    link: function (scope) {
      scope.$on( '$routeChangeSuccess', function () {
        $window._gaq.push(['_trackPageview', $location.path()]);
      });
    }
  };
});

在index.html中,复制并粘贴ga代码片段,但去掉ga('send', 'pageview');

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-XXXXXXXX-X');
</script>

我喜欢给它自己的工厂文件my-google-analytics.js加上自我注入:

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
    }
  ]);