Angular JS 在标签中显示 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21829275/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:57:00  来源:igfitidea点击:

Angular JS shows HTML within the tag

htmlangularjsng-bind-html

提问by Niraj Chauhan

I am trying to insert HTML inside template using ng-bind-html-unsafeattribute. But for some reason its not working.

我正在尝试使用ng-bind-html-unsafe属性在模板中插入 HTML 。但由于某种原因它不起作用。

My code:

我的代码:

<tr class="white two-button" ng-repeat="(key,value) in recommendations | ojoScoreFilter:ojoScore | relevancyScoreFilter:relevancyScore | orderBy:predicate:reverse">
<td>
<div ng-bind-html-unsafe="value.button"></div>
</td>
</tr>

I am not able to see the HTML. If I change ng-bind-html-unsafe="value.button"to ng-bind-html-unsafe="{{value.button}}"then it shows HTML but within the attribute, something like this:

我看不到 HTML。如果我更改ng-bind-html-unsafe="value.button"为,ng-bind-html-unsafe="{{value.button}}"则它显示 HTML 但在属性内,如下所示:

<div ng-bind-html-unsafe="&lt;a class=&quot;action_hrefs full-width bgcolor10 purple-hover flat-button flat-white-button btn&quot; data-value=&quot;947&quot; href=&quot;#&quot;&gt;&lt;i class=&quot;fa fa-lock&quot;&gt;&lt;/i&gt;&nbsp;Unlock&lt;/a&gt;"></div>

回答by Niraj Chauhan

Ok I found solution for this:

好的,我找到了解决方案:

JS:

JS:

$scope.renderHtml = function(html_code)
{
    return $sce.trustAsHtml(html_code);
};

HTML:

HTML:

<p ng-bind-html="renderHtml(value.button)"></p>

回答by Ruben Decrop

make a filter like this

做一个这样的过滤器

.filter('trusted',
   function($sce) {
     return function(ss) {
       return $sce.trustAsHtml(ss)
     };
   }
)

and apply this as a filter to the ng-bind-html like

并将其作为过滤器应用到 ng-bind-html 中

<div ng-bind-html="code | trusted">