AngularJS中取消对HTML片段转义的方法例子
作者:bea
今天尝试用 Rails 做后端提供 JSON 格式的数据, AngularJS 做前端处理 JSON 数据,其中碰到 AngularJS 获取的是一段 HTML 文本,如果直接使用 data-ng-bind 的话是被转义过的,使用 data-ng-bind-html 则可以取消转义。 但是直接使用 data-ng-bind-html 的话会提示错误 代码如下: Error: [$sce:unsafe] Attempting to use an unsafe value
今天尝试用 Rails 做后端提供 JSON 格式的数据, AngularJS 做前端处理 JSON 数据,其中碰到 AngularJS 获取的是一段 HTML 文本,如果直接使用 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>
有用 | 无用
但是直接使用 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>
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- jQuery中removeClass()方法用法实例
- jQuery中addClass()方法用法实例
- js Calender控件使用详解
- js的回调函数详解
- 判断浏览器的内核及版本号方法汇总
- jQuery中removeProp()方法用法实例
- jQuery中prop()方法用法实例
- jQuery中removeAttr()方法用法实例
- jQuery实现鼠标滚轮动态改变样式或效果
- jquery.cookie.js使用指南
- 在Google 地图上实现做的标记相连接
- js获取时间并实现字符串和时间戳之间的转换
- jQuery中attr()方法用法实例
- jQuery实现自定义下拉列表
- 使用javascript实现监控视频播放并打印日志
- jQuery圆形统计图开发实例
- jQuery中:selected选择器用法实例
- jQuery中:checked选择器用法实例
- jQuery中:disabled选择器用法实例