jthomasbailey
jthomasbailey

Reputation: 410

Including Adsense ads inside an ng-repeat loop causes errors

I'm including Google Adsense ads at certain points inside an Angularjs ng-repeat loop like so:

<div ng-repeat="item in items"  >

 <div data-my-ad-sense ng-if="$index == 3">
  //inject an ad inside the third item


   <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
   <!-- ad 2 -->
     <ins class="adsbygoogle"
     style="display:inline-block;width:290px;height:290px"
     data-ad-client="ca-pub-000000"
     data-ad-slot="00000"></ins>
   <script>
   (adsbygoogle = window.adsbygoogle || []).push({});
   </script>


</div>
</div>

And it works fine except that it gives me the error:

Uncaught Error: adsbygoogle.push(): All ins elements in the DOM with class=adsbygoogle already have ads in them

The ads show up where they're supposed to but I'm a little worried Google is going to think I'm using more ads than I'm supposed to. I've tried loading them in partials, but that didn't work either.

Does anyone know how to get rid of that error?

Upvotes: 3

Views: 4100

Answers (2)

Rishi Saraf
Rishi Saraf

Reputation: 1812

Use below directive

var adSenseTpl = '<ins class="ad-div adsbygoogle responsive" style="display:inline-block;width:468px;height:60px" data-ad-client="ca-pub-xxxxx" data-ad-slot="xxxxx"></ins></ins>';
    angular.module('reviewmattersApp')
        .directive('googleAdsense', function($window, $compile) {
        return {
            restrict: 'A',
            transclude: true,
            template: adSenseTpl,
            replace: false,
            link: function postLink(scope, element, iAttrs) {
                    element.html("");
                    element.append(angular.element($compile(adSenseTpl)(scope)));
                    if (!$window.adsbygoogle) {
                        $window.adsbygoogle = [];
                    }
                    $window.adsbygoogle.push({});
            }
        };
    });

In html side

<div  google-adsense>
</div>

Upvotes: 1

user3281733
user3281733

Reputation: 111

Mind that Google allows up to three content units, up to three link units and two search boxes per page.

I got th same error with only three adds on the page. To prevent error to be shown you can replace this line in the google adds code

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

change to

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

Upvotes: 0

Related Questions