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


当前回答

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

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

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

其他回答

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

$rootScope.$on('$stateChangeSuccess', function (event) {
    $window.ga('send', 'pageview', $location.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>

使用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

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

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

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