使用应运行的脚本插入 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13711735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert HTML with scripts that should run
提问by enigment
One part of this app gets HTML back from the server that needs to be shown as live HTML. That's easily done with the ng-bind-html-unsafe="expression"
directive (in Angular 1.0.2 at least).
此应用程序的一部分从需要显示为实时 HTML 的服务器获取 HTML。使用ng-bind-html-unsafe="expression"
指令很容易做到这一点(至少在 Angular 1.0.2 中)。
However, the HTML also has JavaScript that should run, since it defines functions used in the HTML, and that doesn't seem to happen using the directive.
但是,HTML 也有应该运行的 JavaScript,因为它定义了 HTML 中使用的函数,而使用指令似乎不会发生这种情况。
Is there some Angular-style way to do that? Or do I need to explore out-of-band script loading techniques?
有没有一些 Angular 风格的方法来做到这一点?或者我是否需要探索带外脚本加载技术?
(Please let's not discuss whether I should trust the server enough to run java-script it sends me. I do trust the server, I'm aware of the risks, and this is a very specialized situation.)
(请不要讨论我是否应该足够信任服务器来运行它发送给我的 java 脚本。我确实信任服务器,我知道风险,这是一种非常特殊的情况。)
采纳答案by Mark Rajcok
You need jQuery (load it before Angular):
你需要 jQuery(在 Angular 之前加载它):
"we looked into supporting script tags in jqlite, but what needs to be done to get a cross-browser support involves a lot of black magic. For this reason we decided that for now we are just going to recommend that users use jquery along with angular in this particular case" -- https://groups.google.com/d/msg/angular/H4haaMePJU0/5seG803by5kJ
“我们研究了在 jqlite 中支持 script 标签,但需要做什么才能获得跨浏览器支持涉及很多黑魔法。因此我们决定现在我们只建议用户使用 jquery 和在这种特殊情况下有角度” ——https://groups.google.com/d/msg/angular/H4haaMePJU0/5seG803by5kJ
See also AngularJS: How to make angular load script inside ng-include?
回答by pliashkou
I can propose my variant. First you should create directive:
我可以提出我的变体。首先你应该创建指令:
app.directive('html', [ function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.html(attrs.html);
}
}
}]);
Then you can use it inside tag.
然后你可以在标签内使用它。
<div html="{{code}}"></div>