如何通过 AngularJS 模板输出 html

How to output html through AngularJS template?

本文关键字:输出 html 何通过 AngularJS      更新时间:2023-09-26
<h1>{{ revision.title }}</h1>
<div ng-bind-html="revision.content"></div>

标题输出正常,但内容 - 不输出。它有一些html,我收到以下错误:Attempting to use an unsafe value in a safe context.被描述为:http://docs.angularjs.org/error/$sce:unsafe,这很好,但是我如何输出内容,因为其中会有一些html,所以我必须将其设置为{{ revision.content | safe }}或smthn。正确的方法是什么?

编辑:

角度JS版本:1.2

所以解决方法是这样的:

包含来自 http://code.angularjs.org/angular-sanitize.min.js并将其包含在模块中:

var app = angular.module('app', ['ngSanitize']);

然后你可以自由使用ng-bind-html

我知道

这是一个较老的问题,但您也可以在控制器中使用$sce来信任该值:

$scope.revision.content = $sce.trustAsHtml($scope.revision.content);

之后,ng-bind-html将起作用。

我创建了一个ng-html指令,它执行与ng-bind-html-unsafe过去相同的基本操作。 但是,我强烈建议您谨慎使用它。 它可以很容易地打开您的网站受到恶意攻击。因此,在实施之前要知道自己在做什么:

.directive('ngHtml', ['$compile', function($compile) {
    return function(scope, elem, attrs) {
        if(attrs.ngHtml){
            elem.html(scope.$eval(attrs.ngHtml));
            $compile(elem.contents())(scope);
        }
        scope.$watch(attrs.ngHtml, function(newValue, oldValue) {
            if (newValue && newValue !== oldValue) {
                elem.html(newValue);
                $compile(elem.contents())(scope);
            }
        });
    };
}]);

然后,您可以将其用作:

<div ng-html="revision.content"></div>

希望有帮助。

你用的是什么版本?如果您使用的低于 1.2,您可以尝试ngBindHtmlUnsafe

根据官方 AngularJs 文档关于您必须ngBindHtml将 ngSanitize 注入到您的应用程序依赖项中

计算表达式并将生成的 HTML 插入到 元素以安全的方式。默认情况下,生成的 HTML 内容将 使用$sanitize服务进行消毒。要利用这个 功能,确保$sanitize可用,例如,通过 在模块的依赖项中包含 ngSanitize(不在核心中) 棱角分明)。为了在模块的依赖项中使用 ngSanitize, 您需要在应用程序中包含"角度清理.js"。

然后你可以通过以下方式安装ngSanitize模块:

1 - 使用鲍尔

bower install --save angular-sanitize

2 - 使用 npm

npm install --save angular-sanitize

3 - 手动从 code.angularjs.org 路径下载angular-sanitize.js文件,其中包括所有 angularJs 文件类别按版本号,如@Xeen答案

查看有关从 Oficial angularJs github 存储库安装ngSanitize模块的更多信息,用于安装 angular-sanitize