Google ads in Angular js app

This tutorial will help the user to integrate google AdSense in angular js projects. This code will help to monetize the AngularJs application without any issue. Implement the code wherever you want to display in your AngularJS pages.

Please follow the steps below to integrate the AdSense code in AngularJS projects.

Step1: Include the below js file inside the head tag or before the </body>.

<script async src="//"></script>

Above js is for including the google adsense.

Step2: Create directive for Google AdSense.

In the below code, in the variable called “html” you can find the google adsense code which will append the code in html page and below code will return the adsense js dynamically. In “rand” var it will generate the random value to google “data-ad-region” which will make sure page got refereshed.

app.directive('googleAd', ['$timeout', function($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            return $timeout(function() {
                var adsbygoogle, html, rand;
                rand = Math.random();
                html = '<ins class="adsbygoogle" style="display:inline-block;width:300px;height:250px" data-ad-client="ca-pub-XXXXXX" data-ad-slot="XXXXXX"  data-ad-region="page-' + rand + '"></ins>';
                return (adsbygoogle = window.adsbygoogle || []).push({});

Note: Change the “data-ad-client” value to your adsense pub id from google and in “data-ad-slot” add your adsense ad slot from google.

Step3: Include the below html tag in to your angularjs html templates.

<div google-ad></div>

Credits :


Latest posts by W3TWEAKS (see all)


Leave a Reply

Your email address will not be published. Required fields are marked *