I'm working on an Angular (1.6.8) app in which we've implemented the Angulartics library in combination with Google Analytics and Google Tag Manager extensions. This is all working quite well when I follow the instructions that are provided.
But we seem to have a bit of a special situation, the application that we're building is going to be used by multiple people, and based on who is visiting we fetch user settings from our api (using url parameters to know who is visiting at that time).
These users can manage their settings in a different Angular app, it's in this second app that they provide us with they Tag Manager tag, and their Analytics code.
Now comes the hard part (for me at least), Google Tag Manager requires a script tag in the head of our html, but at that time the user settings have not been loaded from our api yet, so we can't provide Google's script with the correct Tag Manager tag (this format: GTM-XXXXX).
Does anyone know of a way to load these scripts correctly when we have dynamically loaded tracking codes? Or is this just not possible?
Thanks for anyone who can provide some insights.
Alright it's been a while and I've figured out a solution that does the job (a while ago), I'll display how I got there in case someone else stumbles upon my question.
It ended up being quite simple, I have the following in my html
<!-- Google Tag Manager -->
<script ng-bind-html="googleTagManagerScript"></script>
<!-- End Google Tag Manager -->
And then in my app.js I fetch the settings through an ajax call and when I have the results I do the following
$rootScope.pixels.tagmanager = value; // store the retrieved Tag Manager code in a variable
$rootScope.googleTagManagerScript = $sce.trustAsHtml("(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','"+$rootScope.pixels.tagmanager.code+"');");
$rootScope.googleTagManagerNoScript = $sce.trustAsHtml("<iframe src='https://www.googletagmanager.com/ns.html?id="+$rootScope.pixels.tagmanager.code+"' height='0' width='0' style='display:none;visibility:hidden'></iframe>");
So basically I put the entire Google script in a variable as soon as everything is available, and ng-bind-html
takes care of the rest.
I hope that makes sense.