Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and adsense

I want to add Google Adsense to my angular app, I found a working example here.

The problem is that I cannot add the html in my template because I'm loading templates in a script tag (<script type="text/ng-template"....) and the script tag of adsense breaks the template.

I tried moving the template to the directive:

app.directive('Adsense', function() {
  return {
    restrict: 'A',
    transclude: true,
    replace: true,
    template: '<div><script type="text/javascript" async="async" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>' +
              '<ins class="adsbygoogle" style="display: inline-block; width: 234px; height: 60px;" ' +
              'data-ad-client="ca-pub-xxxxx" data-ad-slot="xxxxx"></ins>' +
              '<script type="text/javascript">(adsbygoogle = window.adsbygoogle || []).push({});</script></div>',
    link: function ($scope, element, attrs) {}
  }
})

But the javascript is not executed when the directive is set up (which seems to be the wanted behavior AngularJS template. Inner JS not execute). There's another way?

like image 274
Matteo Pagliazzi Avatar asked Sep 19 '13 18:09

Matteo Pagliazzi


1 Answers

Googling: https://gist.github.com/endorama/7369006

/*global angular */
(function (ng) {
  'use strict';

  var app = ng.module('ngLoadScript', []);

  app.directive('script', function() {
    return {
      restrict: 'E',
      scope: false,
      link: function(scope, elem, attr) {
        if (attr.type=='text/javascript-lazy') {
          var code = elem.text();
          var f = new Function(code);
          f();
        }
      }
    };
  });

}(angular));

Then on your template:

<script type="text/javascript-lazy">
  console.log(true);
</script>

Use something like this, or modify to load some specifyc file or use https://github.com/ocombe/ocLazyLoad

There are so many ways.

like image 54
nada Avatar answered Oct 05 '22 23:10

nada