I'm setting up a new app using AngularJS as the frontend. Everything on the client side is done with HTML5 pushstate and I'd like to be able to track my page views in Google Analytics.
我正在用AngularJS作为前端开发一个新应用。客户端上的所有内容都是用HTML5 pushstate完成的,我希望能够在谷歌分析中跟踪我的页面视图。
20 个解决方案
#1
237
If you're using ng-view
in your Angular app you can listen for the $viewContentLoaded
event and push a tracking event to Google Analytics.
如果你在角应用程序中使用ng-view,你可以监听$viewContentLoaded事件,并将跟踪事件推送到谷歌分析。
Assuming you've set up your tracking code in your main index.html file with a name of var _gaq
and MyCtrl is what you've defined in the ng-controller
directive.
假设您已经在主索引中设置了跟踪代码。名称为var _gaq和MyCtrl的html文件就是您在ng-controller指令中定义的。
function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window._gaq.push(['_trackPageView', $location.url()]);
});
}
UPDATE: for new version of google-analytics use this one
更新:对于新版本的google分析使用这个。
function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
}
#2
57
When a new view is loaded in AngularJS
, Google Analytics does not count it as a new page load. Fortunately there is a way to manually tell GA to log a url as a new pageview.
当在AngularJS中加载新视图时,谷歌Analytics不会将其算作新的页面加载。幸运的是,有一种方法可以手动告诉GA将url记录为新的pageview。
_gaq.push(['_trackPageview', '<url>']);
would do the job, but how to bind that with AngularJS?
_gaq。push([' _trackPageview ',' < url > ']);会做这个工作,但是如何将它与AngularJS绑在一起呢?
Here is a service which you could use:
这里有一个你可以使用的服务:
(function(angular) {
angular.module('analytics', ['ng']).service('analytics', [
'$rootScope', '$window', '$location', function($rootScope, $window, $location) {
var track = function() {
$window._gaq.push(['_trackPageview', $location.path()]);
};
$rootScope.$on('$viewContentLoaded', track);
}
]);
}(window.angular));
When you define your angular module, include the analytics module like so:
当你定义角模块时,包括分析模块如下:
angular.module('myappname', ['analytics']);
UPDATE:
更新:
You should use the new Universal Google Analytics tracking code with:
您应该使用新的通用谷歌分析跟踪代码:
$window.ga('send', 'pageview', {page: $location.url()});
#3
48
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function(){
ga('send', 'pageview', $location.path());
});
});
#4
40
Just a quick addition. If you're using the new analytics.js, then:
只是一个快速增加。如果你使用新的分析。js,那么:
var track = function() {
ga('send', 'pageview', {'page': $location.path()});
};
Additionally one tip is that google analytics will not fire on localhost. So if you are testing on localhost, use the following instead of the default create (full documentation)
另外一个提示是谷歌分析不会在localhost上启动。因此,如果您正在本地主机上进行测试,请使用以下命令而不是默认的create(完整的文档)
ga('create', 'UA-XXXX-Y', {'cookieDomain': 'none'});
#5
11
I've created a service + filter that could help you guys with this, and maybe also with some other providers if you choose to add them in the future.
我已经创建了一个服务+过滤器,它可以帮助您解决这个问题,如果您选择在将来添加它们,也可以与其他一些提供者进行合作。
Check out https://github.com/mgonto/angularytics and let me know how this works out for you.
看看https://github.com/mgonto/angularytics,让我知道这对你有什么帮助。
#6
10
Merging the answers by wynnwu and dpineda was what worked for me.
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()
});
});
}
]);
Setting the third parameter as an object (instead of just $location.path()) and using $routeChangeSuccess instead of $stateChangeSuccess did the trick.
将第三个参数设置为对象(而不仅仅是$location.path())),并使用$routeChangeSuccess而不是$stateChangeSuccess实现了这一点。
Hope this helps.
希望这个有帮助。
#7
7
I've created a simple example on github using the above approach.
我使用上面的方法创建了一个关于github的简单示例。
https://github.com/isamuelson/angularjs-googleanalytics
https://github.com/isamuelson/angularjs-googleanalytics
#8
4
If someone wants to implement using directives then, identify (or create) a div in the index.html (just under the body tag, or at same DOM level)
如果有人想要使用指令来实现,那么在索引中识别(或创建)一个div。html(在body标记下面,或者在相同的DOM级别)
<div class="google-analytics"/>
and then add the following code in the directive
然后在指令中添加以下代码。
myApp.directive('googleAnalytics', function ( $location, $window ) {
return {
scope: true,
link: function (scope) {
scope.$on( '$routeChangeSuccess', function () {
$window._gaq.push(['_trackPageview', $location.path()]);
});
}
};
});
#9
4
The best way to do this is using Google Tag Manager to fire your Google Analytics tags based on history listeners. These are built in to the GTM interface and easily allow tracking on client side HTML5 interactions .
最好的方法是使用谷歌标记管理器基于历史侦听器启动谷歌分析标记。它们内置在GTM接口中,很容易就可以跟踪客户端HTML5交互。
Enable the built in History variables and create a trigger to fire an event based on history changes.
启用内置的历史变量,并创建一个触发器,根据历史更改触发事件。
#10
3
In your index.html
, copy and paste the ga snippet but remove the line ga('send', 'pageview');
在您的索引。复制粘贴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>
I like to give it it's own factory file my-google-analytics.js
with self injection:
我喜欢给它自己的工厂文件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
}
]);
#11
3
If you're using ui-router you can subscribe to the $stateChangeSuccess event like this:
如果你正在使用ui-router,你可以订阅$stateChangeSuccess事件,比如:
$rootScope.$on('$stateChangeSuccess', function (event) {
$window.ga('send', 'pageview', $location.path());
});
For a complete working example see this blog post
有关完整的工作示例,请参阅本文
#12
3
Use GA 'set' to ensure routes are picked up for Google realtime analytics. Otherwise subsequent calls to GA will not show in the realtime panel.
使用GA 'set'来确保谷歌实时分析的路由。否则,对GA的后续调用将不会显示在实时面板中。
$scope.$on('$routeChangeSuccess', function() {
$window.ga('set', 'page', $location.url());
$window.ga('send', 'pageview');
});
Google strongly advises this approach generally instead of passing a 3rd param in 'send'. https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
谷歌强烈建议采用这种方法,而不是在“发送”中传递第三个param。https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
#13
3
I am using AngluarJS in html5 mode. I found following solution as most reliable:
我在html5模式下使用AngluarJS。我发现以下的解决方案是最可靠的:
Use angular-google-analytics library. Initialize it with something like:
使用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);
}
]);
After that, add listener on $stateChangeSuccess' and send trackPage event.
然后,在$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
}
});
}
]);
At any moment, when you have your user initalized you can inject Analytics there and make call:
在任何时候,当你让你的用户initalize时,你可以在那里注入分析,然后打电话:
Analytics.set('&uid', user.id);
#14
2
I am using ui-router and my code looks like this:
我使用的是ui-路由器,我的代码是这样的:
$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);
});
This way I can track different states. Maybe someone will find it usefull.
这样我可以跟踪不同的状态。也许有人会觉得它有用。
#15
1
For those of you using AngularUI Router instead of ngRoute can use the following code to track page views.
对于使用AngularUI路由器而不是ngRoute的用户,可以使用以下代码跟踪页面视图。
app.run(function ($rootScope) {
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
ga('set', 'page', toState.url);
ga('send', 'pageview');
});
});
#16
1
Developers creating Single Page Applications can use autotrack, which includes a urlChangeTracker plugin that handles all of the important considerations listed in this guide for you. See the autotrack documentation for usage and installation instructions.
创建单个页面应用程序的开发人员可以使用autotrack,其中包括一个urlChangeTracker插件,它可以处理本指南中列出的所有重要事项。有关使用和安装说明,请参阅自动跟踪文档。
#17
1
I found the gtag()
function worked, instead of the ga()
function.
我发现gtag()函数有效,而不是ga()函数。
In the index.html file, within the <head>
section:
在索引中。html文件,在部分:
<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>
In the AngularJS code:
在AngularJS代码:
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function() {
gtag('config', 'TrackingId', {'page_path': $location.path()});
});
});
Replace TrackingId
with your own Tracking Id.
用您自己的跟踪Id替换TrackingId。
#18
0
Merging even more with Pedro Lopez's answer,
更接近佩德罗·洛佩兹的答案,
I added this to my ngGoogleAnalytis module(which I reuse in many apps):
我把它添加到我的ngGoogleAnalytis模块(我在很多应用程序中重复使用):
var base = $('base').attr('href').replace(/\/$/, "");
in this case, I have a tag in my index link:
在这种情况下,我的索引链接中有一个标签:
<base href="/store/">
it's useful when using html5 mode on angular.js v1.3
当使用html5模式时,它是有用的。js v1.3
(remove the replace() function call if your base tag doesn't finish with a slash /)
(如果您的基本标签没有以斜线/)结束,请删除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()
});
}
);
}
]);
#19
0
I personally like to set up my analytics with the template URL instead of the current path. This is mainly because my application has many custom paths such as message/:id
or profile/:id
. If I were to send these paths, I'd have so many pages being viewed within analytics, it would be too difficult to check which page users are visiting most.
我个人喜欢用模板URL而不是当前路径来建立我的分析。这主要是因为我的应用程序有许多自定义路径,比如消息/:id或概要文件/:id。如果我发送这些路径,我将有如此多的页面在分析中被浏览,这将很难检查哪个页面用户访问最多。
$rootScope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', {
page: $route.current.templateUrl.replace("views", "")
});
});
I now get clean page views within my analytics such as user-profile.html
and message.html
instead of many pages being profile/1
, profile/2
and profile/3
. I can now process reports to see how many people are viewing user profiles.
现在,我在我的分析(如用户配置文件)中获得了干净的页面视图。html和消息。html而不是许多页面是profile/1、profile/2和profile/3。现在,我可以处理报告,看看有多少人查看用户配置文件。
If anyone has any objection to why this is bad practise within analytics, I would be more than happy to hear about it. Quite new to using Google Analytics, so not too sure if this is the best approach or not.
如果有人反对为什么这在分析中是不好的做法,我将非常高兴听到它。使用谷歌分析非常新颖,所以不要太确定这是否是最好的方法。
#20
-3
If you are looking for full control of Google Analytics's new tracking code, you could use my very own Angular-GA.
如果你想要完全控制谷歌分析的新跟踪代码,你可以使用我自己的Angular-GA。
It makes ga
available through injection, so it's easy to test. It doesn't do any magic, apart from setting the path on every routeChange. You still have to send the pageview like here.
它通过注入使ga可用,所以很容易测试。它没有任何魔力,除了在每个路线上设置道路。你仍然需要像这里一样发送pageview。
app.run(function ($rootScope, $location, ga) {
$rootScope.$on('$routeChangeSuccess', function(){
ga('send', 'pageview');
});
});
Additionaly there is a directive ga
which allows to bind multiple analytics functions to events, like this:
此外,还有一个指令ga,允许将多个分析函数绑定到事件上,比如:
<a href="#" ga="[['set', 'metric1', 10], ['send', 'event', 'player', 'play', video.id]]"></a>
#1
237
If you're using ng-view
in your Angular app you can listen for the $viewContentLoaded
event and push a tracking event to Google Analytics.
如果你在角应用程序中使用ng-view,你可以监听$viewContentLoaded事件,并将跟踪事件推送到谷歌分析。
Assuming you've set up your tracking code in your main index.html file with a name of var _gaq
and MyCtrl is what you've defined in the ng-controller
directive.
假设您已经在主索引中设置了跟踪代码。名称为var _gaq和MyCtrl的html文件就是您在ng-controller指令中定义的。
function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window._gaq.push(['_trackPageView', $location.url()]);
});
}
UPDATE: for new version of google-analytics use this one
更新:对于新版本的google分析使用这个。
function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
}
#2
57
When a new view is loaded in AngularJS
, Google Analytics does not count it as a new page load. Fortunately there is a way to manually tell GA to log a url as a new pageview.
当在AngularJS中加载新视图时,谷歌Analytics不会将其算作新的页面加载。幸运的是,有一种方法可以手动告诉GA将url记录为新的pageview。
_gaq.push(['_trackPageview', '<url>']);
would do the job, but how to bind that with AngularJS?
_gaq。push([' _trackPageview ',' < url > ']);会做这个工作,但是如何将它与AngularJS绑在一起呢?
Here is a service which you could use:
这里有一个你可以使用的服务:
(function(angular) {
angular.module('analytics', ['ng']).service('analytics', [
'$rootScope', '$window', '$location', function($rootScope, $window, $location) {
var track = function() {
$window._gaq.push(['_trackPageview', $location.path()]);
};
$rootScope.$on('$viewContentLoaded', track);
}
]);
}(window.angular));
When you define your angular module, include the analytics module like so:
当你定义角模块时,包括分析模块如下:
angular.module('myappname', ['analytics']);
UPDATE:
更新:
You should use the new Universal Google Analytics tracking code with:
您应该使用新的通用谷歌分析跟踪代码:
$window.ga('send', 'pageview', {page: $location.url()});
#3
48
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function(){
ga('send', 'pageview', $location.path());
});
});
#4
40
Just a quick addition. If you're using the new analytics.js, then:
只是一个快速增加。如果你使用新的分析。js,那么:
var track = function() {
ga('send', 'pageview', {'page': $location.path()});
};
Additionally one tip is that google analytics will not fire on localhost. So if you are testing on localhost, use the following instead of the default create (full documentation)
另外一个提示是谷歌分析不会在localhost上启动。因此,如果您正在本地主机上进行测试,请使用以下命令而不是默认的create(完整的文档)
ga('create', 'UA-XXXX-Y', {'cookieDomain': 'none'});
#5
11
I've created a service + filter that could help you guys with this, and maybe also with some other providers if you choose to add them in the future.
我已经创建了一个服务+过滤器,它可以帮助您解决这个问题,如果您选择在将来添加它们,也可以与其他一些提供者进行合作。
Check out https://github.com/mgonto/angularytics and let me know how this works out for you.
看看https://github.com/mgonto/angularytics,让我知道这对你有什么帮助。
#6
10
Merging the answers by wynnwu and dpineda was what worked for me.
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()
});
});
}
]);
Setting the third parameter as an object (instead of just $location.path()) and using $routeChangeSuccess instead of $stateChangeSuccess did the trick.
将第三个参数设置为对象(而不仅仅是$location.path())),并使用$routeChangeSuccess而不是$stateChangeSuccess实现了这一点。
Hope this helps.
希望这个有帮助。
#7
7
I've created a simple example on github using the above approach.
我使用上面的方法创建了一个关于github的简单示例。
https://github.com/isamuelson/angularjs-googleanalytics
https://github.com/isamuelson/angularjs-googleanalytics
#8
4
If someone wants to implement using directives then, identify (or create) a div in the index.html (just under the body tag, or at same DOM level)
如果有人想要使用指令来实现,那么在索引中识别(或创建)一个div。html(在body标记下面,或者在相同的DOM级别)
<div class="google-analytics"/>
and then add the following code in the directive
然后在指令中添加以下代码。
myApp.directive('googleAnalytics', function ( $location, $window ) {
return {
scope: true,
link: function (scope) {
scope.$on( '$routeChangeSuccess', function () {
$window._gaq.push(['_trackPageview', $location.path()]);
});
}
};
});
#9
4
The best way to do this is using Google Tag Manager to fire your Google Analytics tags based on history listeners. These are built in to the GTM interface and easily allow tracking on client side HTML5 interactions .
最好的方法是使用谷歌标记管理器基于历史侦听器启动谷歌分析标记。它们内置在GTM接口中,很容易就可以跟踪客户端HTML5交互。
Enable the built in History variables and create a trigger to fire an event based on history changes.
启用内置的历史变量,并创建一个触发器,根据历史更改触发事件。
#10
3
In your index.html
, copy and paste the ga snippet but remove the line ga('send', 'pageview');
在您的索引。复制粘贴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>
I like to give it it's own factory file my-google-analytics.js
with self injection:
我喜欢给它自己的工厂文件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
}
]);
#11
3
If you're using ui-router you can subscribe to the $stateChangeSuccess event like this:
如果你正在使用ui-router,你可以订阅$stateChangeSuccess事件,比如:
$rootScope.$on('$stateChangeSuccess', function (event) {
$window.ga('send', 'pageview', $location.path());
});
For a complete working example see this blog post
有关完整的工作示例,请参阅本文
#12
3
Use GA 'set' to ensure routes are picked up for Google realtime analytics. Otherwise subsequent calls to GA will not show in the realtime panel.
使用GA 'set'来确保谷歌实时分析的路由。否则,对GA的后续调用将不会显示在实时面板中。
$scope.$on('$routeChangeSuccess', function() {
$window.ga('set', 'page', $location.url());
$window.ga('send', 'pageview');
});
Google strongly advises this approach generally instead of passing a 3rd param in 'send'. https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
谷歌强烈建议采用这种方法,而不是在“发送”中传递第三个param。https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
#13
3
I am using AngluarJS in html5 mode. I found following solution as most reliable:
我在html5模式下使用AngluarJS。我发现以下的解决方案是最可靠的:
Use angular-google-analytics library. Initialize it with something like:
使用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);
}
]);
After that, add listener on $stateChangeSuccess' and send trackPage event.
然后,在$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
}
});
}
]);
At any moment, when you have your user initalized you can inject Analytics there and make call:
在任何时候,当你让你的用户initalize时,你可以在那里注入分析,然后打电话:
Analytics.set('&uid', user.id);
#14
2
I am using ui-router and my code looks like this:
我使用的是ui-路由器,我的代码是这样的:
$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);
});
This way I can track different states. Maybe someone will find it usefull.
这样我可以跟踪不同的状态。也许有人会觉得它有用。
#15
1
For those of you using AngularUI Router instead of ngRoute can use the following code to track page views.
对于使用AngularUI路由器而不是ngRoute的用户,可以使用以下代码跟踪页面视图。
app.run(function ($rootScope) {
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
ga('set', 'page', toState.url);
ga('send', 'pageview');
});
});
#16
1
Developers creating Single Page Applications can use autotrack, which includes a urlChangeTracker plugin that handles all of the important considerations listed in this guide for you. See the autotrack documentation for usage and installation instructions.
创建单个页面应用程序的开发人员可以使用autotrack,其中包括一个urlChangeTracker插件,它可以处理本指南中列出的所有重要事项。有关使用和安装说明,请参阅自动跟踪文档。
#17
1
I found the gtag()
function worked, instead of the ga()
function.
我发现gtag()函数有效,而不是ga()函数。
In the index.html file, within the <head>
section:
在索引中。html文件,在部分:
<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>
In the AngularJS code:
在AngularJS代码:
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function() {
gtag('config', 'TrackingId', {'page_path': $location.path()});
});
});
Replace TrackingId
with your own Tracking Id.
用您自己的跟踪Id替换TrackingId。
#18
0
Merging even more with Pedro Lopez's answer,
更接近佩德罗·洛佩兹的答案,
I added this to my ngGoogleAnalytis module(which I reuse in many apps):
我把它添加到我的ngGoogleAnalytis模块(我在很多应用程序中重复使用):
var base = $('base').attr('href').replace(/\/$/, "");
in this case, I have a tag in my index link:
在这种情况下,我的索引链接中有一个标签:
<base href="/store/">
it's useful when using html5 mode on angular.js v1.3
当使用html5模式时,它是有用的。js v1.3
(remove the replace() function call if your base tag doesn't finish with a slash /)
(如果您的基本标签没有以斜线/)结束,请删除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()
});
}
);
}
]);
#19
0
I personally like to set up my analytics with the template URL instead of the current path. This is mainly because my application has many custom paths such as message/:id
or profile/:id
. If I were to send these paths, I'd have so many pages being viewed within analytics, it would be too difficult to check which page users are visiting most.
我个人喜欢用模板URL而不是当前路径来建立我的分析。这主要是因为我的应用程序有许多自定义路径,比如消息/:id或概要文件/:id。如果我发送这些路径,我将有如此多的页面在分析中被浏览,这将很难检查哪个页面用户访问最多。
$rootScope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', {
page: $route.current.templateUrl.replace("views", "")
});
});
I now get clean page views within my analytics such as user-profile.html
and message.html
instead of many pages being profile/1
, profile/2
and profile/3
. I can now process reports to see how many people are viewing user profiles.
现在,我在我的分析(如用户配置文件)中获得了干净的页面视图。html和消息。html而不是许多页面是profile/1、profile/2和profile/3。现在,我可以处理报告,看看有多少人查看用户配置文件。
If anyone has any objection to why this is bad practise within analytics, I would be more than happy to hear about it. Quite new to using Google Analytics, so not too sure if this is the best approach or not.
如果有人反对为什么这在分析中是不好的做法,我将非常高兴听到它。使用谷歌分析非常新颖,所以不要太确定这是否是最好的方法。
#20
-3
If you are looking for full control of Google Analytics's new tracking code, you could use my very own Angular-GA.
如果你想要完全控制谷歌分析的新跟踪代码,你可以使用我自己的Angular-GA。
It makes ga
available through injection, so it's easy to test. It doesn't do any magic, apart from setting the path on every routeChange. You still have to send the pageview like here.
它通过注入使ga可用,所以很容易测试。它没有任何魔力,除了在每个路线上设置道路。你仍然需要像这里一样发送pageview。
app.run(function ($rootScope, $location, ga) {
$rootScope.$on('$routeChangeSuccess', function(){
ga('send', 'pageview');
});
});
Additionaly there is a directive ga
which allows to bind multiple analytics functions to events, like this:
此外,还有一个指令ga,允许将多个分析函数绑定到事件上,比如:
<a href="#" ga="[['set', 'metric1', 10], ['send', 'event', 'player', 'play', video.id]]"></a>