0

I am trying to dynamically insert the google analytics id into the script. Something like this where {{configs[0].ga_id}} stores the id.

<script>
google code....

ga('create', '{{configs[0].ga_id}}', 'auto');
</script>

this is not working. I have also tried all of these but all are failing.

'{configs[0].ga_id}', 
'configs[0].ga_id', 
+ configs[0].ga_id +

Any ideas?

UPDATE: per MarkoCen

I added this directive and my html looks like this. When inspecting the element the id is displayed properly "UA-XXXXXXXX-1" but in the console.log of of the directive I see this "{{configs[0].ga_id}}"

<google-analytics id="{{configs[0].ga_id}}"></google-analytics>

app.directive('googleAnalytics', function(){
  return {
    restrict: 'E',
    replace: true,
    template: function(elem, attr){
      console.log(attr.id);
      return "<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', '" + attr.id + "', 'auto');</script>"
    }
  }
})
Jason
  • 1,091
  • 4
  • 19
  • 40

1 Answers1

1

because Google Analytics is not a part of Angular, and the template syntax won't working within a <script> tag, you should create a directive to wrap the code:

 angular.module('app').directive('googleAnalytics', function(){
     return {
       restrict: 'E',
       replace: true,
       template: function(){
          var configs = [...]; //first get configs from somewhere...
          return "<script>google code... ga('create', '" + configs[0].ga_id + "', 'auto');</script>"
       }
     }
 })

then you could insert this directive into <head>

<!DOCTYPE html>
<html ng-app="app">
   <head>
       <google-analytics></google-analytics>
   </head>
</html>
MarkoCen
  • 2,189
  • 13
  • 24