zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

方法HTML 例子 取消 转义 片段 angularjs
2023-06-13 09:15:39 时间

今天尝试用Rails做后端提供JSON格式的数据,AngularJS做前端处理JSON数据,其中碰到AngularJS获取的是一段HTML文本,如果直接使用data-ng-bind的话是被转义过的,使用data-ng-bind-html则可以取消转义。

但是直接使用data-ng-bind-html的话会提示错误

复制代码代码如下:

Error:[$sce:unsafe]Attemptingtouseanunsafevalueinasafecontext.

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(){
   varrequest=$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部分
复制代码代码如下:
<divclass="post-bodymarkup-body"data-ng-bind-html="post.trustedBody"></div>