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


当前回答

我使用ui-router和我的代码看起来像这样:

$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams){
  /* Google analytics */
  var path = toState.url;
  for(var i in toParams){
    path = path.replace(':' + i, toParams[i]);
  }
  /* global ga */
  ga('send', 'pageview', path);
});

这样我就可以跟踪不同的状态。也许有人会觉得它有用。

其他回答

把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就可以了。

希望这能有所帮助。

如果你正在使用ui-router,你可以像这样订阅$stateChangeSuccess事件:

$rootScope.$on('$stateChangeSuccess', function (event) {
    $window.ga('send', 'pageview', $location.path());
});

有关完整的工作示例,请参阅这篇博客文章

开发人员创建单页应用程序可以使用autotrack,其中包括一个urlChangeTracker插件,该插件可以处理本指南中列出的所有重要考虑事项。有关使用和安装说明,请参阅autotrack文档。

使用GA 'set'来确保路由被谷歌实时分析拾取。否则,后续对GA的调用将不会显示在实时面板中。

$scope.$on('$routeChangeSuccess', function() {
    $window.ga('set', 'page', $location.url());
    $window.ga('send', 'pageview');
});

谷歌强烈建议使用这种方法,而不是在send中传递第三个参数。 https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

我用上面的方法在github上创建了一个简单的例子。

https://github.com/isamuelson/angularjs-googleanalytics