【问题标题】:Angular JS shows HTML within the tagAngular JS 在标签内显示 HTML
【发布时间】:2014-03-16 18:15:10
【问题描述】:

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

我的代码:

<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>

我看不到 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>

【问题讨论】:

  • 尝试在你的模块中包含'ngSanitize'模块,在你的标记中包含ng-bind-html
  • 您使用的是哪个版本的 Angular? ng-bind-html-unsafe 在 Angular 1.2 版中被删除。
  • @DavinTryon 我使用的是 1.2.9
  • 然后查看ng-bind-html。您需要将此指令与$sce 服务结合使用。

标签: html angularjs ng-bind-html


【解决方案1】:

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

JS:

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

HTML:

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

【讨论】:

  • 哇,这是唯一有效的!我已经尝试了一切,谢谢:)
  • 这也是唯一对我有用的解决方案。请务必将 $sce 注入您的控制器。
  • 这可行,但似乎有点矫枉过正。我必须将 $sce 注入每个控制器吗?并且必须将 renderHtml 函数添加到每个需要 html 的控制器?
  • 这也是唯一对我有用的解决方案。在其他 SO 帖子中找到的已接受答案:stackoverflow.com/questions/9381926/… 不起作用。
  • 为了让它工作,请确保将 $sce 注入到控制器中定义的函数中,如下所示:myApp.controller('myCtrl', function($scope, $sce) {
【解决方案2】:

制作这样的过滤器

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

并将其作为过滤器应用到 ng-bind-html 之类的

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

【讨论】:

  • 上面接受的答案得到了很多票,但我认为这个解决方案是一个更好的答案。这样做将解决必须将 $sce 注入每个将显示 html 的控制器的问题。不过我还是新手,请随时纠正我!
猜你喜欢
  • 1970-01-01
  • 2015-11-11
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 2015-01-20
  • 1970-01-01
相关资源
最近更新 更多