我正在使用AngularJS作为前端设置一个新的应用程序。客户端上的一切都是用HTML5推送状态完成的,我希望能够在谷歌分析中跟踪我的页面视图。
当前回答
我使用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);
});
这样我就可以跟踪不同的状态。也许有人会觉得它有用。
其他回答
我使用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);
});
这样我就可以跟踪不同的状态。也许有人会觉得它有用。
使用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
把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就可以了。
希望这能有所帮助。
我发现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()]);
});
}
};
});
推荐文章
- AngularJS控制器的生命周期是什么?
- $destroy是否删除事件监听器?
- 用布尔值将单选按钮绑定到模型
- AngularJS只适用于单页应用程序吗?
- angular.js中的内联条件
- 如何突出显示当前菜单项?
- 如何使用AngularJS获取url参数
- 谷歌标签管理器和谷歌分析之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- Ng-repeat结束事件
- 缓存一个HTTP 'Get'服务响应在AngularJS?
- 从ng-click获取原始元素
- Angular JS:当我们已经有了具有作用域的指令控制器时,指令的link函数还需要什么?
- Angularjs的ng-model不能在ng-if中工作
- AngularJS禁用了开发机器上的部分缓存