AngularJS with Google Analytics

I want to add Google Analytics code to my AngularJS application.

I use Ruby On Rails as a backend framework. An AngularJS application.html.erbRails file is only uploaded on first request.

So, I put the Google analytics code inside the event viewcontentLoad.

 $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 to insert Google Analytics code or not.

+1
source share
1 answer

This answer to Tracking Analytics page views with Angular.js might be helpful.

One comment suggests that this is a good way to do this:

$rootScope.$on('$routeChangeSuccess', ...)
+2
source

Source: https://habr.com/ru/post/1692223/


All Articles