我正在尝试将Google 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 :(得分: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>
答案 1 :(得分:0)
您也可以尝试在JS文件中创建类似的功能
previousAction
此方法找到具有提供的 ID 的div,然后创建一个 INS 元素并将其附加到该div。
在窗口加载时调用此方法,如下所示:
function createAndAppendAdsElement(id, adUnitID) {
var parent = document.getElementById(id);
var ele = document.createElement('ins');
ele.style.display = 'block';
ele.className = 'adsbygoogle';
ele.setAttribute('data-ad-client', 'ca-pub-XXXXXXXX');
ele.setAttribute('data-ad-slot', adUnitID);
ele.setAttribute('data-ad-format', 'auto');
ele.setAttribute('data-full-width-responsive', 'true');
parent.appendChild(ele);
(adsbygoogle = window.adsbygoogle || []).push({});
}