Reputation: 73
I'm trying putting Google Adsense ads inside an Angularjs ng-repeat like below. But its not working
<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>
I see below error in my console.
Uncaught Error: adsbygoogle.push(): All ins elements in the DOM with class=adsbygoogle already have ads in them
Is there someway to show adsense ads inside ng-repeat?
Upvotes: 4
Views: 2073
Reputation: 516
You can also try creating a function like this in JS file
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({});
}
This method finds a div with provided ID and then create a INS element and append it to that div.
Call this method on window load as below:
window.onload = function () {
createAndAppendAdsElement('elementOne', 'your_ad_unit_number');
createAndAppendAdsElement('elementTwo', 'your_ad_unit_number');
createAndAppendAdsElement('elementThree', 'your_ad_unit_number');
createAndAppendAdsElement('elementFour', 'your_ad_unit_number');
createAndAppendAdsElement('elementFive', 'your_ad_unit_number');
};
Upvotes: 0
Reputation: 1812
You can do it using 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: 4