我正在使用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就可以了。

希望这能有所帮助。

其他回答

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

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

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

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

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

如果你正在寻找谷歌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>

我个人喜欢用模板URL而不是当前路径来设置我的分析。这主要是因为我的应用程序有许多自定义路径,如message/:id或profile/:id。如果我要发送这些路径,我将在分析中有如此多的页面被查看,这将很难检查哪个页面用户访问最多。

$rootScope.$on('$viewContentLoaded', function(event) {
    $window.ga('send', 'pageview', {
        page: $route.current.templateUrl.replace("views", "")
    });
});

我现在在我的分析中获得干净的页面视图,如user-profile.html和message.html,而不是许多页面是profile/1, profile/2和profile/3。我现在可以通过处理报告来查看有多少人正在浏览用户资料。

如果有人对为什么这是一种糟糕的分析实践有任何异议,我很乐意听听。对谷歌Analytics的使用非常陌生,所以不太确定这是否是最好的方法。

结合佩德罗·洛佩兹的回答,

我把这个添加到我的ngGoogleAnalytis模块(我在许多应用程序中重用):

var base = $('base').attr('href').replace(/\/$/, "");

在这种情况下,我有一个标签在我的索引链接:

  <base href="/store/">

当在angular.js v1.3上使用html5模式时,它很有用

(如果base标签没有以斜杠/结束,则删除replace()函数调用)

angular.module("ngGoogleAnalytics", []).run(['$rootScope', '$location', '$window',
    function($rootScope, $location, $window) {
      $rootScope.$on('$routeChangeSuccess',
        function(event) {
          if (!$window.ga) { return; }
          var base = $('base').attr('href').replace(/\/$/, "");

          $window.ga('send', 'pageview', {
            page: base + $location.path()
          });
        }
      );
    }
  ]);