Howto: monetize your Angular JS project with Google Adsense

Here is a tutorial abouts using Adsense on a single page application made with Angular js.

A little bit of theory

# Default Google Adsense code

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-XXXXXXXXXXXXXXX"
     data-ad-slot="XXXXXXXXXXXXXXX"
     data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

The default Google code is made up by three parts:

  • A remote javascript inclusion
  • An <ins> tag with some data attributes
  • A javascript call to adsbygoogle.push(): when push() is invoked, every <ins> tag is replaced by the appropriate ad.

Ok, let’s do it

To make that code work with Angular, we must split its parts so that the <ins> tag goes on the view, the inclusion stays close to the end of the page <body> and the push() is called inside a controller. Here is an example:

<!doctype html>
<html ng-app="myApp">
  <head>
    <title>My Angular App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
  </head>
  <body>
    <div ng-controller="MyCtrl">
      <ins class="adsbygoogle"
           style="display:block"
           data-ad-client="ca-pub-XXXXXXXXXXXXX"
           data-ad-slot="XXXXXXXXXXXXX"
           data-ad-format="auto">
      </ins>
    </div>
      
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <script>
      angular.module('myApp', []).controller('MyCtrl', function($scope){
        try {
          (adsbygoogle = window.adsbygoogle || []).push({});
        } catch(e){}
      });
    </script>
  </body>
</html>

It’s a good idea to place push() into a try – catch block as it will throw an exception if it gets called too many times or there are no more elements to fill, in this way we won’t show annoying messages in the browser’s console.

A little trick if you are using ngRoute

If you use ngRoute to manage urls, views and controllers, then you must be sure that the view is ready before trying to load any ads, $viewContentLoaded is your friend: load the ads only when the view is ready or they won’t appear.

<script>
  angular.module('myApp', []).controller('MyCtrl', function($scope){
    $scope.$on('$viewContentLoaded', function(){
     try {
       (adsbygoogle = window.adsbygoogle || []).push({});
     } catch(e){}
   });
  });
</script>

Thanks for reading, comments and improvements to this article are always welcome.