zoukankan      html  css  js  c++  java
  • Angular.js数据绑定时自动转义html标签及内容

    angularJS在进行数据绑定时默认是以字符串的形式数据,也就是对你数据中的html标签不进行转义照单全收,这样提高了安全性,防止html标签的注入攻击,但有时候需要,特别是从数据库读取带格式的文本时,无法正常的显示在页面中。

    而要对html进行转义,则需要在数据绑定的html标签中使用ng-bind-html属性,该属性依赖与$sanitize,也就是需要引入angular-sanitize.js文件,并在module定义时注入该服务ngSanitize。比如:

    html:

    <span ng-controller = "myCtr" ng-bind-html = "htmlStr"></span>

    javascript:

    function myCtr($scope){
    
      $scope.htmlStr = '<p style="color:white;background:#f60;"></p>';
    
    };

    这样可以实现html转义,但是有个问题是style这种标签会被angularJS认为是不安全的所以统统自动过滤掉,而为了保留这些就需要开启非安全模式。

    如何让自动加载的数据转义html标签呢?实际上还有一种绑定方式:

    html:

    <div ng-repeat = "article in articles">
    
      <div class="panel-heading">
    
        <h4><b>{{article.title}}</b></h4>
    
      </div>
    
      <div class="panel-body">
    
        <article id="word-display" ng-bind-html="article.content | trustHtml">
    
        </article>
    
      </div>
    
    </div>

    javascript:

    success(function(data){
    
      $scope.articles = data;
    
    });
    
    myApp.filter('trustHtml',function($sce){
    
      return function(input){
    
        return $sce.trustAsHtml(input);
    
      }
    
    });

    其中$sce是angularJS自带的安全处理模块,$sce.trustAsHtml(input)方法便是将数据内容以html的形式进行解析并返回。将此过滤器添加到ng-bind-html所绑定的数据中,便实现了在数据加载时对与html标签的自动转义。

    我要成为酷酷的人http://www.cnblogs.com/CooLLYP/
  • 相关阅读:
    Javascript自动垃圾收集机制
    Javascript深入浅出(二)
    Javascript深入浅出(一)
    递归&循环&迭代&遍历&枚举,知多少
    事件流、事件处理程序和事件对象
    弹性布局学习笔记
    css3 伪元素
    css3伪类选择器nth-of-type,:nth-last-of-type,:first-of-type,:last-of-type,:only-of-type
    css3结构伪类选择器first-child,last-child,nth-child(),nth-last-child(),only-child
    css3状态伪类选择器:checked修改按钮默认样式
  • 原文地址:https://www.cnblogs.com/CooLLYP/p/6500602.html
Copyright © 2011-2022 走看看