Google ads in Angular js app

By | January 11, 2017

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 :


Author: CV

I am a Front-end Developer, graduate of Information Technology, and founder of I have 12+ years commercial experience providing front-end development, producing high quality responsive websites and exceptional user experience.