Angular.js和Adsense

Dav*_*wak 11 adsense angularjs transclusion angularjs-directive

我正在尝试在我的angular.js应用上投放广告,并且我已经完成了一些阅读并发现无法复制和粘贴普通的adsense代码.

我听说你应该"将它包装在带有翻译的指令中",我能找到的唯一例子是另一个Stackoverflow帖子: AngularJs和AddThis社交插件

有人可以帮助提供有关如何使用Google Adsense进行此操作的指导吗?

zie*_*sni 18

你需要创建一个指令

yourApp.directive('ads', function() {
    return {
        restrict: 'A',
        templateUrl: 'partiels/adsTpl',
        controller: function(){
            (adsbygoogle = window.adsbygoogle || []).push({});
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

在我的案例中创建一个包含广告代码的模板"partiels/adsTpl.html"

<ins class="adsbygoogle"
 style="display:inline-block;width:300px;height:250px"
 data-ad-client="ca-pub-00000000"
 data-ad-slot="000000"></ins>
Run Code Online (Sandbox Code Playgroud)

将指令添加到您的页面

 <div data-ads></div>
Run Code Online (Sandbox Code Playgroud)

在angularjs之前将adSense js调用放在主页的head部分

<head>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
....
Run Code Online (Sandbox Code Playgroud)

et voila,这对我来说非常有用

  • 太棒了!这正是我一直在寻找的,它很简单,适用于AngularJs! (2认同)

Pab*_*one 15

您应该像这样对adSense脚本执行包装指令...

<div data-my-ad-sense>
  <!-- Google AdSense -->
  <script async src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
  <ins class="adsbygoogle"
       style="display:inline-block;width:728px;height:90px"
       data-ad-client="ca-pub-0000000000"
       data-ad-slot="0000000000"></ins>
  <script>
  (adsbygoogle = window.adsbygoogle || []).push({});
  </script>
</div>
Run Code Online (Sandbox Code Playgroud)

并将此指令添加到您的指令中......

directive('myAdSense', function() {
  return {
    restrict: 'A',
    transclude: true,
    replace: true,
    template: '<div ng-transclude></div>',
    link: function ($scope, element, attrs) {}
  }
})
Run Code Online (Sandbox Code Playgroud)

这是adSense异步代码.