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


当前回答

我发现gtag()函数工作,而不是ga()函数。

在index.html文件中,<head>部分:

<script async src="https://www.googletagmanager.com/gtag/js?id=TrackingId"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'TrackingId');
</script>

在AngularJS代码中:

app.run(function ($rootScope, $location) {
  $rootScope.$on('$routeChangeSuccess', function() {
    gtag('config', 'TrackingId', {'page_path': $location.path()});
  });
});

用您自己的跟踪Id替换TrackingId。

其他回答

如果有人想实现using指令,那么就在index.html中标识(或创建)一个div(就在body标签下面,或在相同的DOM级别)。

<div class="google-analytics"/>

然后在指令中添加如下代码

myApp.directive('googleAnalytics', function ( $location, $window ) {
  return {
    scope: true,
    link: function (scope) {
      scope.$on( '$routeChangeSuccess', function () {
        $window._gaq.push(['_trackPageview', $location.path()]);
      });
    }
  };
});

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

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

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

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

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

我把这个添加到我的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()
          });
        }
      );
    }
  ]);

我在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);