当前位置: 移动技术网 > IT编程>开发语言>JavaScript > AngularJS中取消对HTML片段转义的方法例子

AngularJS中取消对HTML片段转义的方法例子

2018年06月18日  | 移动技术网IT编程  | 我要评论
今天尝试用 rails 做后端提供 json 格式的数据, angularjs 做前端处理 json 数据,其中碰到 angularjs 获取的是一段 html 文本,如果

今天尝试用 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>

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网