new_comer
new_comer

Reputation: 49

how to add google analytics script in angular js app?

Hello I am new to angularJs and i want to implement google analytics script in my angular app, which is having more thann 20pages and i am using routing. If anyone can help me in that, I will be very gratefull. If you can give a example where to add the script and how. Thanks in advance.

Upvotes: 1

Views: 1667

Answers (1)

new_comer
new_comer

Reputation: 49

Here I am providing answer to my question: First of all add you google analytics code to your index.html inside of script tag

<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','https://www.google-analytics.com/analytics.js','ga');

          ga('create', 'UA-xxxxxxxx-x', 'auto');
          ga('send', 'pageview');
</script>

Then create a function in app.js file

$rootScope.$on('$locationChangeStart', function() {
            ga('set', 'page', $location.path());
            ga('send', 'pageview');
});

And you are good to go.

Upvotes: 1

Related Questions