AngularJs注入谷歌分析脚本标签

时间:2016-06-16 15:06:10

标签: javascript angularjs google-analytics

我正在尝试将我的谷歌分析脚本注入我的应用程序。我在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','https://www.google-analytics.com/analytics.js','ga');
    </script>

这是我的指令:

app.directive('googleAnalytics', function(configFactory){
  return {
    restrict: 'E',
    replace: true,
    templateUrl: '../views/gaScript.html',
    link: function(scope,element,attrs){
      configFactory.getconfigs().then(function(configs) {
          scope.gid = configs[0].ga_id;
      });
    }
  };
})

该指令在gaScript.html中使用此模板来注入正确的ga ID

<script>ga('create', '{{gid}}', 'auto');</script>

这是正文中的html标记,被指令

取代
<google-analytics></google-analytics>

问题是我认为页面是以字符串形式读取此<script>ga('create', '{{gid}}', 'auto');</script>而不是解释脚本标记

1 个答案:

答案 0 :(得分:0)

根据@mparnisari评论,我能够让它正常工作。如果这有助于其他人,这是最终结果。

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

这是指令:

app.directive('googleAnalytics', function(configFactory){
  return {
    restrict: 'E',
    replace: true,
    link: function(scope,element,attrs){
      configFactory.getconfigs().then(function(configs) {
          scope.gid = configs[0].ga_id;
          var scriptTag = angular.element(document.createElement("script"));
              scriptTag.text("ga('create', '"+scope.gid+"', 'auto');")
              element.append(scriptTag);
      });
    }
  };
})

这是index.html体内的html标签,指令使用

<google-analytics></google-analytics>

我的系统有多个用户。此代码允许每个用户使用自己的GA ID

相关问题