Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
jthomasbailey Avatar asked Feb 17 '26 23:02

jthomasbailey


1 Answers

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>
like image 142
Rishi Saraf Avatar answered Feb 20 '26 00:02

Rishi Saraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!