我想将 Google Adsense 添加到我的 Angular 应用程序,我找到了一个工作示例 here .
问题是我无法在我的模板中添加 html,因为我在脚本标记 ( <script type="text/ng-template"....
) 和 script
中加载模板adsense 标签破坏了模板。
我尝试将模板移动到指令:
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) {}
}
})
但是当指令被设置时 javascript 没有被执行(这似乎是想要的行为 AngularJS template. Inner JS not execute )。还有别的办法吗?
最佳答案
谷歌搜索: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));
然后在你的模板上:
<script type="text/javascript-lazy">
console.log(true);
</script>
使用类似这样的东西,或修改以加载一些指定的文件或使用 https://github.com/ocombe/ocLazyLoad
有很多方法。
关于javascript - AngularJS 和 Adsense,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18901913/