2014-06-17 88 views
4

我正在嘗試將Google Adsense廣告放入Angularjs ng-repeat內,如下所示。但它不起作用Adsense廣告不工作angularjs ng-repeat

<div ng-repeat="item in items" 
<div ng-include src="view.getItem($index)"></div> 
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> 
<div ng-if="$index == 0" google-adsense> 
    <ins class="adsbygoogle responsive" 
     style="display:inline-block;width:468px;height:60px" 
     data-ad-client="ca-pub-" 
     data-ad-slot=""></ins> 
    <script> 
     (adsbygoogle = window.adsbygoogle || []).push({}); 
    </script> 
</div> 
</div> 

我在我的控制檯中看到下面的錯誤。

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

有沒有辦法在ng-repeat中顯示adsense廣告?

+0

你爲什麼要加入同一個腳本多次做 – chandu

回答

4

您可以使用指令

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({}); 
     } 
    }; 
}); 

在HTML端

<div google-adsense> 
</div>