Angularjs:preVIEW消毒HTML [英] Angularjs: preview sanitized html

查看:205
本文介绍了Angularjs:preVIEW消毒HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请找到 plnkr

我要显示一些HTML preVIEW。的HTML是在服务器已经消毒(对于例如:&放大器; LT; B和; GT; HELLO&放大器; LT; / B&放大器; GT;)。我怎样才能显示HTML表单。在这个例子中,我要显示 myHtml2 作为显示 MYHTML (第preVIEW)。

HTML

 < D​​IV NG控制器=myController的>
      < D​​IV NG绑定-HTML =MYHTML>< / DIV>
      < D​​IV NG绑定-HTML =myHtml2>< / DIV>
      < D​​IV> {{myHtml2}}< / DIV>
    < / DIV>

JS

  myApp.controller('myController的',['$范围,$ SCE,功能myController的($范围,$ SCE){
  $ scope.myHtml =< B> HELLO< / B>中;
  $ scope.myHtml2 =放大器; LT; B和; GT;&HELLO放大器; LT; / B&放大器; GT;
}]);

退出

  HELLO
< B> HELLO< / B>
&放大器; LT; B和; GT;&HELLO放大器; LT; / B&放大器; GT;


解决方案

您只需要使用的 $ sce.trustAsHtml unsanitize HTML客户端上:的 http://plnkr.co/edit/h2loxWsPJOELhNvkfHmK?p=$p$pview

  //来源:http://stackoverflow.com/questions/1912501/unescape-html-entities-in-javascript
功能htmlDe code(输入){
  变种E =使用document.createElement('DIV');
  e.innerHTML =输入;
  返回e.childNodes.length === 0? :e.childNodes [0] .nodeValue;
}myApp.controller('myController的',['$范围,$ SCE,功能myController的($范围,$ SCE){
  $ scope.myHtml =< B> HELLO< / B>中;
  $ scope.myHtml2 = $ sce.trustAsHtml(htmlDe code(与& LT; B和; GT;&HELLO放大器; LT; / B&放大器; GT;));}]);

htmlDe code 来自:的在Javascript UNESCAPE HTML实体?

不过,我不建议采用这种方法。它给人的感觉非常的hackish我怀疑可能会导致您的网站的安全漏洞。

Please find the plnkr

I want to display some html preview. The html is already sanitized at the server (for eg: "<b>HELLO</b>"). How can I display the html form. In the example, I want to display myHtml2 as displayed for myHtml (first preview).

html

 <div ng-controller="myController">
      <div ng-bind-html="myHtml"></div>
      <div ng-bind-html="myHtml2"></div>
      <div >{{myHtml2}}</div>
    </div>

js

myApp.controller('myController', ['$scope', '$sce', function myController($scope, $sce){
  $scope.myHtml = "<b>HELLO</b>";
  $scope.myHtml2 = "&lt;b&gt;HELLO&lt;/b&gt;";      
}]);

out

HELLO
<b>HELLO</b>
&lt;b&gt;HELLO&lt;/b&gt;

解决方案

You just need to use $sce.trustAsHtml and unsanitize HTML on your client: http://plnkr.co/edit/h2loxWsPJOELhNvkfHmK?p=preview

// From: http://stackoverflow.com/questions/1912501/unescape-html-entities-in-javascript
function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

myApp.controller('myController', ['$scope', '$sce', function myController($scope, $sce){
  $scope.myHtml = "<b>HELLO</b>";
  $scope.myHtml2 = $sce.trustAsHtml(htmlDecode("&lt;b&gt;HELLO&lt;/b&gt;"));

}]);

htmlDecode from: Unescape HTML entities in Javascript?

However, I would not recommend taking this approach. It feels very hackish and I suspect could lead to vulnerabilities on your site.

这篇关于Angularjs:preVIEW消毒HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆