Next.js - How to make sure <title> is set by the time the history change event fires? - next.js

In my Next.js app, I'm setting the <title> tag for individual pages using the recommended method:
import Head from 'next/head'
export default () => <>
<Head><title>My page title</title></Head>
</>
Here's the problem: when the history change event fires, the value of document.title doesn't always match the current URL.
You can test it yourself:
Router.events.on("routeChangeComplete", () => {
if ('browser' in process) {
console.log('--------');
console.log(window.location.href);
console.log(document.title);
}
});
Navigating between pages, you should observe that URL & title are often mismatched. The value of URL is always right, but the value of title is all over the place. It can have:
the right value
the value it had on the previous page
no value at all
This is an issue when using analytics, specifically GTM - Google Tag Manager, which uses the current URL & page title to uniquely identify visited pages.
I've had this issue with Next.js 7, and upgrading to 8 hasn't fixed it.
Do you know of any way to solve this problem? Maybe delaying the history change event until the first render of a component under /pages/?
Thanks!

This is a small hack. setTimeout(()=>{console.log(document.title)}, 0)

I found a work-around by intercepting events sent to window.dataLayer.push and adding a one-second delay in case the event is gtm.historyChange.
Here's my GtagScript component that I'm adding to <Head> under _document.js:
export const GtagScript = () => {
function intercept() {
const scriptTag = document.querySelector('#gtm-js');
if (scriptTag !== null)
scriptTag.addEventListener('load', () => {
window.dataLayer.pushOrig = window.dataLayer.push;
window.dataLayer.push = (e) => {
if (e.event === 'gtm.historyChange') {
setTimeout(function () {
window.dataLayer.pushOrig(e);
console.log(`URL: ${window.location.href} Title: ${document.title}`);
}, 1000);
} else {
window.dataLayer.pushOrig(e);
}
};
});
}
return <>
<script
id="gtm-js"
async
src={`https://www.googletagmanager.com/gtm.js?id=${GA_TRACKING_ID}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}');
${intercept.toString()}
intercept();`
}}
/>
</>
};
I'll wait a while to see if an official fix comes from the ZEIT team. My solution doesn't actually answer the question. It doesn't set <title>, it just defers the event, which isn't optimal.

You can use setInterval
const firstPageViewEvent = setInterval(() => {
if (document.title) {
// send pageview event
clearInterval(firstPageViewEvent);
}
}, 200);

Related

Disable Woocomerce register button after one click

Hello I would like to disable the woocommmerce register page button after one click to avoid multiple clicks.
I have searched the forums and found a bunch of solutions for custom forms and I've tried the following JS code but had no luck. I have a feeling I am setting the wrong selector because I cannot for the life of me figure out what the correct selector for the default register button is.
<script>
function disableButton() {
var btn = document.getElementById('woocommerce-register-nonce');
btn.disabled = true;
btn.innerText = 'Posting...'
}
</script>
I've also tried :
<script>
jQuery('woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit').live('click', function (e) {
var self = this;
$(this).attr("disabled", "disabled");
do_something();
setTimeout(function () {
$(self).removeAttr('disabled');
}, 10000);
});
</script>
Some guidance would be very much appreciated.
Update!
Based on Onboardmass's suggestion I have corrected the selector and got it partially working using jquery.
<script>
jQuery('.woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit').click(function(){
jQuery(this).attr("disabled", "disabled");
});
</script>
The button now gets disabled on click however the issue I'm facing now is that the form does not get submitted.
The issue you're facing is because the selector is incorrect. It should be .woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit.
For anyone else who may need this I was able to figure this one out by reading through the suggestions and other threads I found. Thank you Onboardmass & Martin for the guidance!
The time out function is required for the click to register.
<script>
$(document).ready(function () {
$(".woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit").click(function () {
setTimeout(function () { disableButton(); }, 0);
});
function disableButton() {
$(".woocommerce-Button.woocommerce-button.button.woocommerce-form-register__submit").prop('disabled', true);
}
});
</script>

How to prevent Google AdWords script from prevent reloading in SPA?

I have a SPA built on React JS stack. I'm using react-router to navigate through pages and i need to implement Google AdWords on my website.
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = 333333;
w.google_conversion_label = "33333";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
I embed this code in body and i run goog_report_conversion when i click on button which navigates me to another page. Which is unwanted behaviour for SPA.
<Link
className="btn btn-primary"
to="/settings"
onClick={() => goog_report_conversion('site.name/settings')}
>Go to settings</Link>
The problem is that once I do it, it fully reloads my webpage.
I know that this line causes the problem
window.location = url;
But without it script doesn't work.
I also tried to create this event in Google Tag Manager and follow advices given here Google Tag Manager causes full page reload in SPA - React but it didn't help me.
Have anyone faced same problem implementing AdWords in SPA? How did you solve it?
I feel that the implementation example for the asynchronous Remarketing/Conversion snippet is needlessly complex. Here's something that we used in a similar scenario.
First we define a little helper function that we can reuse:
<script type="text/javascript">
function triggerConversion(conversionID, conversionLabel) {
if (typeof(window.google_trackConversion) === "function") {
window.google_trackConversion({
google_conversion_id: conversionID,
google_conversion_label: conversionLabel,
google_remarketing_only: false
});
}
}
</script>
then we include Google's async conversion script (ideally somewhere where it doesn't block rendering):
<script type="text/javascript"
src="http://www.googleadservices.com/pagead/conversion_async.js"
charset="utf-8">
</script>
And now you can track conversions on any element, like so, to adapt your example:
<Link
className="btn btn-primary"
onClick={() => triggerConversion(333333, "33333")}
>Go to settings</Link>

FullCalendar - Retrieve fileId of Attachments in Google Calendar

I'm hoping to find some help retrieving the Google Calendar attachment fileId through FullCalendar v2.9.0.
The Google calendar is dedicated to this project and is public as is the Drive folder containing image files which are the attachments - one image per event. I am new to the details of Javascript, but I've searched and researched quite a bit. I have not been able to find an example or tutorial that is close enough to what I'm trying to do that I can understand.
My project involves a month view FullCalendar where a user clicks an event, the event background highlights and a sidebar div populates with title, dateTime, description, location, and attachment image file. The user would browse through multiple events with the sidebar updating accordingly.
Here's what I've done so far:
The Google calendar elements are populating and updating correctly except for the image attachment.
I can hard code the HTML in gcal.html with a URL appended with the attachment fileId and get the image in the sidebar. The image, of course, is static though.
Using Google API Explorer calendar.events.get and entering calendarId, eventId, and simple API key, all of which are retrievable from FullCalendar, API Explorer returns the attachment fileId,
(Note that the fileUrl below works in a browser pulling up a viewer, but does not work in my HTML. This one does though: "https://drive.google.com/uc?export=view&id=0B5Nk_tOCzCISaWdqYy1DYnF6SzA")
From API Explorer
Execute without OAuth
calendar.events.get executed 16 minutes ago time to execute: 282 ms
Request
GET https://www.googleapis.com/calendar/v3/calendars/c6kag4dlhqs7m160s3t3lfggak%40group.calendar.google.com/events/u9a5fuoqkfmkm2c20vpn75krf4?fields=attachments(fileId%2CfileUrl)&key={YOUR_API_KEY}
Response
200
- Show headers -
{
"attachments": [
{
"fileUrl": "https://drive.google.com/file/d/0B5Nk_tOCzCISaWdqYy1DYnF6SzA/view?usp=drive_web",
"fileId": "0B5Nk_tOCzCISaWdqYy1DYnF6SzA"
}
]
}
I've tried what seems like endless combinations of statements, basically guessing, at the right syntax in a gcal.html eventClick function. I've also been trying to add code to events.push in gcal.js. This is the only place where I can find other event elements referenced.
My current setup with "alert(event.fileid);" under eventClick ingcal.html and "attachments: entry.fileid" under events.push in gcal.js returns an alert "undefined". In gcal.js a few lines down I notice "successArgs = [ events ].concat(Array.prototype.slice.call(arguments, 1)); // forward other jq args". I'm wondering if FullCalendar returns all fields for an event?
gcal.html (head)
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link href='../fullcalendar.css' rel='stylesheet' />
<link href='../fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='../lib/moment.min.js'></script>
<script src='../lib/jquery.min.js'></script>
<script src='../fullcalendar.min.js'></script>
<script src='../gcal.js'></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
eventLimit: 4,
googleCalendarApiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
events: {
googleCalendarId: 'c6kag4dlhqs7m160s3t3lfggak#group.calendar.google.com'
},
//$('#calendar'.fullCalendar( 'clientEvents' [, filter ] )
// Need to highlight next upcoming event on page load
// var filter = (events, event.start > getdate(new))
eventClick: function(event, events ) {
alert(event.fileid);
//eventRender: function(event, element, view) {
// Need to reset highlight on prevoiusly clicked event
// element.css('background-color', '#5777c8');
//}
//$('#calendar').fullCalendar( 'updateEvents' );
$( "#sidebar2" ).html(event.title);
$( "#sidebar3" ).html(event.start.format('dddd MMM. Do'));
$( "#sidebar4" ).html(event.start.format('h:mm a'));
$( "#sidebar5" ).html(event.description);
$( "#sidebar6" ).html(
'<a style= color:#a2cadc; href=http://' +
event.location + ' target="_blank">' +
"More Band Info" + '</a>'
);
$(this).css('background-color', '#5777c8');
return false;
console.log
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
});
</script>
gcal.js (line 122 to end)
return $.extend({}, sourceOptions, {
googleCalendarId: null, // prevents source-normalizing from happening again
url: url,
data: data,
startParam: false, // `false` omits this parameter. we already included it above
endParam: false, // same
timezoneParam: false, // same
success: function(data) {
var events = [];
var successArgs;
var successRes;
if (data.error) {
reportError('Google Calendar API: ' + data.error.message, data.error.errors);
}
else if (data.items) {
$.each(data.items, function(i, entry) {
var url = entry.htmlLink || null;
// make the URLs for each event show times in the correct timezone
if (timezoneArg && url !== null) {
url = injectQsComponent(url, 'ctz=' + timezoneArg);
}
events.push({
id: entry.id,
title: entry.summary,
start: entry.start.dateTime || entry.start.date,
// try timed. will fall back to all-day
end: entry.end.dateTime || entry.end.date, // same
url: url,
location: entry.location,
description: entry.description,
attachments: entry.fileid // tryiing to find the attachment reference
});
});
// call the success handler(s) and allow it to return a new events array
successArgs = [ events ].concat(Array.prototype.slice.call(arguments, 1));
// forward other jq args
successRes = applyAll(success, this, successArgs);
if ($.isArray(successRes)) {
return successRes;
}
}
return events;
}
});
}
// Injects a string like "arg=value" into the querystring of a URL
function injectQsComponent(url, component) {
// inject it after the querystring but before the fragment
return url.replace(/(\?.*?)?(#|$)/, function(whole, qs, hash) {
return (qs ? qs + '&' : '?') + component + hash;
});
}
});
Any help to get this working would be greatly appreciated.

Loading Google Places Autocomplete Async Angular 2

I am trying to instantiate a Google Places Autocomplete input within an Angular 2 component. I use this code to do it:
loadGoogle() {
let autocomplete = new google.maps.places.Autocomplete((this.ref.nativeElement), { types: ['geocode'] });
let that = this
//add event listener to google autocomplete and capture address input
google.maps.event.addListener(autocomplete, 'place_changed', function() {
let place = autocomplete.getPlace();
that.place = place;
that.placesearch = jQuery('#pac-input').val();
});
autocomplete.addListener()
}
Normally, I believe, I would use the callback function provided by the Google API to ensure that it is loaded before this function runs, but I do not have access to it within a component's scope. I am able to load the autocomplete input 90% of the time, but on slower connections I sometimes error out with
google is not defined
Has anyone figured out how to ensure the Google API is loaded within a component before instantiating.
Not sure whether this will help, but I just use a simple script tag in my index.html to load Google API and I never get any error. I believe you do the same as well. I post my codes here, hope it helps.
Note: I use Webpack to load other scripts, except for Google Map API.
<html>
<head>
<base href="/">
<title>Let's Go Holiday</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Google Map -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<your-key>&libraries=places"></script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
And then in your component:
...
declare var google: any;
export class SearchBoxComponent implements OnInit {
ngOnInit() {
// Initialize the search box and autocomplete
let searchBox: any = document.getElementById('search-box');
let options = {
types: [
// return only geocoding results, rather than business results.
'geocode',
],
componentRestrictions: { country: 'my' }
};
var autocomplete = new google.maps.places.Autocomplete(searchBox, options);
// Add listener to the place changed event
autocomplete.addListener('place_changed', () => {
let place = autocomplete.getPlace();
let lat = place.geometry.location.lat();
let lng = place.geometry.location.lng();
let address = place.formatted_address;
this.placeChanged(lat, lng, address);
});
}
...
}
I used it the same way as explained above but as per google page speed i was getting this suggestion,
Remove render-blocking JavaScript:
http://maps.googleapis.com/…es=geometry,places&region=IN&language=en
So i changed my implementation,
<body>
<app-root></app-root>
<script src="http://maps.googleapis.com/maps/api/js?client=xxxxx2&libraries=geometry,places&region=IN&language=en" async></script>
</body>
/* Now in my component.ts */
triggerGoogleBasedFn(){
let _this = this;
let interval = setInterval(() => {
if(window['google']){
_this.getPlaces();
clearInterval(interval);
}
},300)
}
You can do one more thing, emit events once the value(google) is received,& trigger your google task
inside them.

Tracking Google Analytics Page Views with AngularJS

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.
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.
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.
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
function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
}
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.
_gaq.push(['_trackPageview', '<url>']); would do the job, but how to bind that with 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()});
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function(){
ga('send', 'pageview', $location.path());
});
});
Just a quick addition. If you're using the new analytics.js, then:
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)
ga('create', 'UA-XXXX-Y', {'cookieDomain': 'none'});
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.
Merging the answers by wynnwu and dpineda was what worked for me.
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.
Hope this helps.
I've created a simple example on github using the above approach.
https://github.com/isamuelson/angularjs-googleanalytics
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 .
Enable the built in History variables and create a trigger to fire an event based on history changes.
In your index.html, copy and paste the ga snippet but remove the line 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:
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
}
]);
I found the gtag() function worked, instead of the ga() function.
In the index.html file, within the <head> section:
<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:
app.run(function ($rootScope, $location) {
$rootScope.$on('$routeChangeSuccess', function() {
gtag('config', 'TrackingId', {'page_path': $location.path()});
});
});
Replace TrackingId with your own Tracking Id.
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 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()]);
});
}
};
});
For those of you using AngularUI Router instead of ngRoute can use the following code to track page views.
app.run(function ($rootScope) {
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
ga('set', 'page', toState.url);
ga('send', 'pageview');
});
});
If you're using ui-router you can subscribe to the $stateChangeSuccess event like this:
$rootScope.$on('$stateChangeSuccess', function (event) {
$window.ga('send', 'pageview', $location.path());
});
For a complete working example see this blog post
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.
$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
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.
I am using AngluarJS in html5 mode. I found following solution as most reliable:
Use angular-google-analytics library. Initialize it with something like:
//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.
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:
Analytics.set('&uid', user.id);
I am using ui-router and my code looks like this:
$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.
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.
$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.
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.
I suggest using the Segment analytics library and following our Angular quickstart guide. You’ll be able to track page visits and track user behavior actions with a single API. If you have an SPA, you can allow the RouterOutlet component to handle when the page renders and use ngOnInit to invoke page calls. The example below shows one way you could do this:
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
ngOnInit() {
window.analytics.page('Home');
}
}
I’m the maintainer of https://github.com/segmentio/analytics-angular. With Segment, you’ll be able to switch different destinations on-and-off by the flip of a switch if you are interested in trying multiple analytics tools (we support over 250+ destinations) without having to write any additional code. 🙂
Merging even more with Pedro Lopez's answer,
I added this to my ngGoogleAnalytis module(which I reuse in many apps):
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
(remove the replace() function call if your base tag doesn't finish with a slash /)
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()
});
}
);
}
]);
If you are looking for full control of Google Analytics's new tracking code, you could use my very own 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.
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:

Resources