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


当前回答

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

其他回答

我个人喜欢用模板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()
          });
        }
      );
    }
  ]);

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

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

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

我在html5模式下使用AngluarJS。我发现以下解决方案是最可靠的:

使用angular-google-analytics库。用如下代码初始化它:

//Do this in module that is always initialized on your webapp    
angular.module('core').config(["AnalyticsProvider",
  function (AnalyticsProvider) {
    AnalyticsProvider.setAccount(YOUR_GOOGLE_ANALYTICS_TRACKING_CODE);

    //Ignoring first page load because of HTML5 route mode to ensure that page view is called only when you explicitly call for pageview event
    AnalyticsProvider.ignoreFirstPageLoad(true);
  }
]);

之后,在$stateChangeSuccess上添加监听器,并发送trackPage事件。

angular.module('core').run(['$rootScope', '$location', 'Analytics', 
    function($rootScope, $location, Analytics) {
        $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams, options) {
            try {
                Analytics.trackPage($location.url());
            }
            catch(err) {
              //user browser is disabling tracking
            }
        });
    }
]);

在任何时候,当你的用户初始化时,你可以在那里注入分析并调用:

Analytics.set('&uid', user.id);
app.run(function ($rootScope, $location) {
    $rootScope.$on('$routeChangeSuccess', function(){
        ga('send', 'pageview', $location.path());
    });
});