javascript - AngularJS 和 Adsense

标签 javascript angularjs angularjs-directive adsense

我想将 Google Adsense 添加到我的 Angular 应用程序,我找到了一个工作示例 here .

问题是我无法在我的模板中添加 html,因为我在脚本标记 ( <script type="text/ng-template".... ) 和 script 中加载模板adsense 标签破坏了模板。

我尝试将模板移动到指令:

app.directive('Adsense', function() {
  return {
    restrict: 'A',
    transclude: true,
    replace: true,
    template: '<div><script type="text/javascript" async="async" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>' +
              '<ins class="adsbygoogle" style="display: inline-block; width: 234px; height: 60px;" ' +
              'data-ad-client="ca-pub-xxxxx" data-ad-slot="xxxxx"></ins>' +
              '<script type="text/javascript">(adsbygoogle = window.adsbygoogle || []).push({});</script></div>',
    link: function ($scope, element, attrs) {}
  }
})

但是当指令被设置时 javascript 没有被执行(这似乎是想要的行为 AngularJS template. Inner JS not execute )。还有别的办法吗?

最佳答案

谷歌搜索:https://gist.github.com/endorama/7369006

/*global angular */
(function (ng) {
  'use strict';

  var app = ng.module('ngLoadScript', []);

  app.directive('script', function() {
    return {
      restrict: 'E',
      scope: false,
      link: function(scope, elem, attr) {
        if (attr.type=='text/javascript-lazy') {
          var code = elem.text();
          var f = new Function(code);
          f();
        }
      }
    };
  });

}(angular));

然后在你的模板上:

<script type="text/javascript-lazy">
  console.log(true);
</script>

使用类似这样的东西,或修改以加载一些指定的文件或使用 https://github.com/ocombe/ocLazyLoad

有很多方法。

关于javascript - AngularJS 和 Adsense,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18901913/

相关文章:

javascript - 使用匿名函数和存储在变量中的函数作为回调参数 JavaScript

javascript - 使用 javascript 或 jQuery 激活加载时的复选框

javascript - AngularJS:从 &lt;script type ="application/json"> 获取 json 数据到 Controller

javascript - Angular URL 'trustAsResourceUrl' 不起作用

AngularJS 在自定义指令中包装 ui-select

javascript - 了解 AngularJS 指令方法绑定(bind)是否默认为 angular.noop

javascript - HTML5/Javascript 以一定 Angular 在屏幕上移动对象

javascript - json - 如何正确创建 json 数组

javascript - Angular 应用程序无法在浏览器上正确呈现

javascript - AngularJS : How to bind data from dynamic url?