为 AngularJS 动态插入 Google 标签管理器 (gtag.js) 跟踪 ID

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

我需要为 AngularJS 动态插入 Google 标签管理器 (gtag.js)。我管理一个多租户站点,其中每个租户的跟踪 ID 都是唯一的。

我们以前这样做过(使用 Google Analytics - analytics.js 的旧方法)是这样的:

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());
    });
  }
}

如何使用新的 gtag 方法完成此操作?

<!-- 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>

解决了。

在此感谢 Luke Boris 的回答:

这里结合Chris Anker的回答:

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');
    });
  }
}