Javascript 使用 angularJS 解析 ng-bind 中的 html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14888822/
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
parse html inside ng-bind using angularJS
提问by Edgar Martinez
I'm having issue with angularJs. My application requests some data from the server and one of the values from the data returned from the server is a string of html. I am binding it in my angular template like this
我有 angularJs 的问题。我的应用程序从服务器请求一些数据,从服务器返回的数据中的一个值是一串 html。我像这样将它绑定在我的角度模板中
<div>{{{item.location_icons}}</div>
but as you might expect what I see is not the icons images but the markup basically the stuff in the div looks like
但正如你所料,我看到的不是图标图像,而是标记基本上 div 中的东西看起来像
"<i class='my-icon-class'/>"
which is not what I want.
这不是我想要的。
anyone know what I can do to parse the html in the transclusion
任何人都知道我可以做些什么来解析嵌入中的 html
回答by Tosh
回答by Mher Aghabalyan
As ng-bind-html-unsafe is deprecated, you can use this code instead.
由于 ng-bind-html-unsafe 已弃用,您可以改用此代码。
You need to create function inside your controller:
您需要在控制器中创建函数:
$scope.toTrustedHTML = function( html ){
return $sce.trustAsHtml( html );
}
and use something like this in your view:
并在您看来使用这样的东西:
<span ng-bind-html='toTrustedHTML( myHTMLstring )'></span>
Don't forget to inject $sce:
不要忘记注入 $sce:
AppObj.controller('MyController', function($scope, $sce) {
//your code here
});
回答by Pierre Broucz
A better way is to use $compileinstead of ng-bind-html-unsafe.
更好的方法是使用$compile而不是ng-bind-html-unsafe.
See: http://docs.angularjs.org/api/ng.$compile
请参阅:http: //docs.angularjs.org/api/ng.$compile
Lastly, at the moment, the last version of angularJS (release candidate 1.2.0) do not have any ng-bind-html-unsafedirective. So I really encourage you to consider this option before any future update of your app. ( ng-bind-html-unsafemay/will not working any more...)
最后,目前,angularJS 的最后一个版本(候选版本 1.2.0)没有任何ng-bind-html-unsafe指令。所以我真的鼓励你在你的应用程序的任何未来更新之前考虑这个选项。(ng-bind-html-unsafe可能/将不再工作......)
http://code.angularjs.org/1.2.0rc1/docs/api/ng.directive:ngBindHtml
http://code.angularjs.org/1.2.0rc1/docs/api/ng.directive:ngBindHtml

