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?


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.

链接地址: http://www.djcxy.com/p/16002.html

上一篇: JAXBException:不是类上的有效属性

下一篇: AngularJS和AdSense