angularjs - $sce.trustAsHtml 不起作用

标签 angularjs plaintext ng-bind-html

我正在从 REST api 获取帖子内容。 我得到的内容:“<p>测试帖子正文</p>

首先,我正在解析纯文本

data[i].postBody = $sce.trustAsHtml(data[i].postBody);

在我这样做并尝试使用 ng-bind-html 显示之后

<span ng-bind-html="value.postBody"></span>

并继续显示为 html。

输出:

<p>test post body</p>

我无法显示没有 html 标签的文本

请帮帮我!

最佳答案

首先使用 htmlDecode 函数转义 HTML 实体

HTML:

<div ng-bind-html="value.postBody"></div>

JS:

angular.module('ngApp', ['ngSanitize'])
.controller('controller1', ['$scope','$sce', function($scope, $sce) {
    // Some Code ...
    ...
    ...
    function htmlDecode(input) {
        var e = document.createElement('div');
        e.innerHTML = input;
        return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
    }
    data[i].postBody = $sce.trustAsHtml(htmlDecode(data[i].postBody));
    ...
    ...
    // Some Code ...
}]);

fiddle 链接:http://jsfiddle.net/3J25M/771/

关于angularjs - $sce.trustAsHtml 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40085890/

相关文章:

file - JSONP 文件的正确扩展名是什么?

html - Angular JS 在标签内显示 HTML

angularjs - Angular ng-bind-html 在 Safari iOS7 上写入 HTML 2 次

javascript - Angular Material 菜单在移动设备中触发点击事件 2 次

javascript - 如何以 "right"方式内联初始化 angular.js Controller 数据

XSLT 输出纯文本表

jsp - 纯文本 JSP 响应

javascript - 如何对使用 ng-bind-html 渲染的可编辑 DIV 中的文本进行 ng 建模?

html - 使用 angularjs 动态更改元素的 css 类

javascript - 父/子模型 AngularJS 上的默认 ngOptions