如何使用自定义角度指令加载脚本? [英] How to load a script using custom angular directive?
问题描述
我正在尝试在自定义角度指令中加载脚本。现在,它只是在DOM中添加脚本标记,但它没有加载它。
I am trying to load a script in my custom angular directive. Right now, it is simply adding script tag in DOM but it is not loading it.
angular.module('myApp')
.directive('rjHeader', function () {
return {
restrict: 'E',
template : function(e,a){
return '<script type="text/javascript" charset="utf-8" src="https://my.web.com/path/' + a.locale + '/some.js" ></script>';
}
};
});
并且在html中
And in html
<div rj-Header locale="en_US"></div>
在浏览器中打开页面时,它正确添加预期的脚本。
When opening the page in browser, it correctly adds the intended script.
<script type="text/javascript" charset="utf-8" src="https://my.web.com/path/en_US/some.js" ></script>
但实际上并没有加载这个.js文件。如果我简单地将此行粘贴到我的html,那么它按预期工作。如何使用自定义角度指令注入脚本?
But this doesn't actually loads this .js file. If I simple copy paste this line to my html then it works as expected. How can I inject script using custom angular directive?
推荐答案
这里似乎有点不对,但如果你真的想这样做你可以在你的指令元素上附加一个脚本标记:
Something seems a little wrong here, but if you really wanted to do this you could just append a script tag to your directive's element:
app.directive('loadDirective', function() {
return {
restrict: 'E',
link: function($scope, $el) {
var script = document.createElement('script');
script.src = '//cdnjs.cloudflare.com/ajax/libs/emojione/1.3.0/lib/js/emojione.min.js'
$el.append(script);
}
}
});
这篇关于如何使用自定义角度指令加载脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!