Mat*_*zzi 7 javascript adsense angularjs angularjs-directive
我想在我的角度应用程序中添加Google Adsense,我在这里找到了一个有效的例子.
问题是我无法在模板中添加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) {}
}
})
Run Code Online (Sandbox Code Playgroud)
但是当指令设置时,javascript不会被执行(这似乎是想要的行为AngularJS模板.内部JS没有执行).还有另外一种方法吗?
谷歌搜索: 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));
Run Code Online (Sandbox Code Playgroud)
然后在你的模板上:
<script type="text/javascript-lazy">
console.log(true);
</script>
Run Code Online (Sandbox Code Playgroud)
使用类似的东西,或修改以加载某些指定文件或使用https://github.com/ocombe/ocLazyLoad
有很多方法。
| 归档时间: |
|
| 查看次数: |
1431 次 |
| 最近记录: |