I want to add Google Analytics code to my AngularJS app.
I am using Ruby On Rails as a backend framework. The AngularJS application.html.erb
file of Rails loads only on the first request.
So, I am putting google analytics code inside viewcontentLoad
event.
$rootScope.$on('$viewContentLoaded', function () {
(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-XXXX-Y', 'auto');
// ga('send', 'pageview');
ga('send', 'pageview', {'page': $location.path()});
});
I don't know if this is a valid way of inserting Google Analytics code or not.
This answer on Tracking Google Analytics Page Views with Angular.js may be helpful.
One of the comments suggests that this is a good way to do it: