AngularJS with Google Analytics

2019-08-06 12:24发布

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.

1条回答
Bombasti
2楼-- · 2019-08-06 13:07

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:

$rootScope.$on('$routeChangeSuccess', ...)
查看更多
登录 后发表回答