11

I'm trying to put ads on my angular.js app, and I've done some reading and discovered it isn't possible to just copy and paste the normal adsense code.

I've heard you are supposed to "wrap it in a directive with a transclusion," and the only example I can find of this is another Stackoverflow post: AngularJs and AddThis social plugin

Can someone help give guidance about how to go about doing this with Google Adsense?

4

4 回答 4

18

你需要创建一个指令

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

在我的例子中使用您的广告代码创建一个模板“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>

将指令添加到您的页面

 <div data-ads></div>

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

<head>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
....

瞧,这对我来说非常适合

于 2014-03-29T18:28:44.370 回答
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>

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

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

这是 adSense 异步代码。

于 2013-07-07T12:27:39.230 回答
2

我不确定按照 AdSense T&C 执行以下操作是否有效。

在更改 url 之前删除所有 google 相关变量

Object.keys(window).filter(function(k) { return /google/.test(k) }).forEach(
        function(key) {
            delete(window[key]);
        }
    );
于 2014-10-06T10:10:29.733 回答
0

在AngularJS控制器中,添加一个init()函数,添加一行

(adsbygoogle = window.adsbygoogle || []).push({});

init()然后在您的视图 html 文件中调用此函数。

另请参阅
https://github.com/featen/ags/blob/master/webapp/js/controllers/dict.js

于 2014-05-05T22:07:25.403 回答