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


当前回答

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

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

其他回答

如果你在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() });
  });
}

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

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

app.run(function ($rootScope, $location) {
    $rootScope.$on('$routeChangeSuccess', function(){
        ga('send', 'pageview', $location.path());
    });
});

我使用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);
});

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

如果你正在寻找谷歌Analytics的新跟踪代码的完全控制,你可以使用我自己的Angular-GA。

它使ga可以通过注入得到,因此易于测试。除了在每个routeChange上设置路径外,它没有做任何神奇的事情。你还是需要像这样发送浏览量。

app.run(function ($rootScope, $location, ga) {
    $rootScope.$on('$routeChangeSuccess', function(){
        ga('send', 'pageview');
    });
});

另外,还有一个指令ga,它允许将多个分析函数绑定到事件上,就像这样:

<a href="#" ga="[['set', 'metric1', 10], ['send', 'event', 'player', 'play', video.id]]"></a>