【转】AngularJS 取消对 HTML 片段的转义
2015-07-07 09:35
609 查看
今天尝试用 Rails 做后端提供 JSON 格式的数据, AngularJS 做前端处理 JSON 数据,其中碰到 AngularJS 获取的是一段 HTML 文本,如果直接使用
但是直接使用
HTML 片段需要先使用
在我这里 Angular 通过 API 或取的所有文章中,每篇文章有个 html_body 属性是经过 Markdown 或者 Org 渲染过的 HTML 片段。
在通过 API 获取 JSON 数据后,使用 AngularJS 提供的
AngularJS 部分
HTML 部分
亲测可用,附上原文地址(可能打不开)
原文 http://blog.sloger.info/posts/cancel-escape-html-partial-in-angularjs
data-ng-bind的话是被转义过的,使用
data-ng-bind-html则可以取消转义。
但是直接使用
data-ng-bind-html的话会提示错误
Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
HTML 片段需要先使用
$sce.trustAsHtml(html_in_string)将标记为信任,然后才可以使用
data-ng-bind-html="html_in_string"取消转义。
在我这里 Angular 通过 API 或取的所有文章中,每篇文章有个 html_body 属性是经过 Markdown 或者 Org 渲染过的 HTML 片段。
在通过 API 获取 JSON 数据后,使用 AngularJS 提供的
angular.forEach方法对每个 post 的 html_body 进行标记,并将结果保存为 trustedBody, 然后在 HTML 中使用
data-ng-bind-html="post.trustedBody"即可以取消转义。
AngularJS 部分
Blog.controller('PostsController', function ($scope, $http, $sce) { $scope.posts = []; $scope.syncPosts = function () { var request = $http.get('http:/localhost:3000/posts.json'); request.success(function (response) { $scope.posts = angular.forEach(angular.fromJson(response), function (post) { post.trustedBody = $sce.trustAsHtml(post.html_body); }); }); }; $scope.syncPosts(); });
HTML 部分
<div class="post-body markup-body" data-ng-bind-html="post.trustedBody"></div>
亲测可用,附上原文地址(可能打不开)
原文 http://blog.sloger.info/posts/cancel-escape-html-partial-in-angularjs
相关文章推荐
- AngularJS取消对HTML转义
- angularJS基于WEB的静态页面模板
- angularjs时间轴
- AngularJs自定义指令详解(10) - 执行次序
- AngularJs 简单实现全选,多选操作
- AngularJS-入门篇
- AngularJS简介-起步阶段
- AngularJS的启动过程分析
- angularjs客户端实现压缩图片文件并上传实例
- Angular Module声明和获取重载
- angularjs客户端实现压缩图片文件并上传实例
- AngularJS自定义表单控件
- AngularJS自定义表单验证器
- 使用AngularJs需要注意的事项
- AngularJS自定义表单验证
- AngularJS学习笔记1
- angularjs应用骨架
- AngularJs自定义指令详解(9) - terminal
- AngularJs自定义指令详解(8) - priority
- AngularJs自定义指令详解(7) - multiElement