Insert Google Tag Manager (gtag.js) Tracking Id dynamically for AngularJS

Issue

I need to insert Google Tag Manager (gtag.js) dynamically for AngularJS. I manage a multi-tenant site where the Tracking Id is unique per tenant.

We did this previously (the old way using Google Analytics – analytics.js) like this:

index.html –

    <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');
    </script>

app.controller.js –

function setupAnalytics() {
  var googleTagEnabled = $settings.checkTrue('Analytics/GoogleTagEnabled');
  var googleTag = $settings['Analytics/GoogleTag'];
  if (googleTagEnabled) {
    $window.ga('create', googleTag, 'auto');

    $rootScope.$on('$stateChangeSuccess', function (event) {
      $window.ga('send', 'pageview', $location.path());
    });
  }
}

How can this be done using the new gtag method?

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-YY"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-XXXXXXXXX-YY');
</script>

Solution

Solved it.

Kudos to Luke Boris’s answer here:
https://stackoverflow.com/a/66530446/1098620

Combine with Chris Anker’s answer here:
https://stackoverflow.com/a/48124899/1098620

index.html

<!-- no code here. -->

app.controller.js

function setupAnalytics() {
  var googleTagEnabled = $settings.checkTrue('Analytics/GoogleTagEnabled');
  var googleTag = $settings['Analytics/GoogleTag'];
  if (googleTagEnabled) {       
    // Setting dataLayer & gtag to window because I'm using a custom code text field in a tag management system
    window.dataLayer = window.dataLayer || [];
    window.gtag =
    window.gtag ||
    function() {
        window.dataLayer.push(arguments);
    };
    window.gtag("js", new Date());
    window.gtag("config", googleTag);

    // Set initial gtag/js?id=<first ID> script to <head>
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    script.src = "//www.googletagmanager.com/gtag/js?id=" + googleTag;
    document.getElementsByTagName("head")[0].appendChild(script);

    $rootScope.$on('$stateChangeSuccess', function (event) {
        $window.gtag('config', googleTag, {'page_path': $location.path()});
        $window.gtag('event', 'page_view');
    });
  }
}

Answered By – nesterenes

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published