如何通过 AngularJS 模板输出 html
How to output html through AngularJS template?
<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
- 使用Jade输出HTML(在ng个重复内)
- 输出 html 表单数据
- 如何通过 AngularJS 模板输出 html
- Ajax 输出 html 注释
- 显示查询输出 HTML 中的图像
- HTML 代码不适用于 jquery 调用,而是输出 HTML 代码
- Html.ActionLink onclick JavaScript 函数未被调用,并且函数名称在输出 HTML 中已损
- Javascript -使用字符串输出HTML
- 如何正确使用jQuery从php输出html字符串
- 为什么.html()不输出html标签
- 如何获得一个变量's输出html值
- Twitter-text.js输出html作为纯文本
- 多行文本文件输出html
- 如何使用XSLT匹配元素和输出HTML
- 输出HTML代码
- 输出HTML时出现意外的令牌错误
- 用JavaScript输出HTML实体
- 在rjerb模板中输出HTML
- 从angularjs过滤器输出HTML,无需ng绑定HTML
- 获取实际输出HTML的函数