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/
  • 相关阅读:
    visual studio 2013 生成依赖项关系图出错
    redHat 安装mono 错误
    redHat 安装mono 错误
    msdn帮助,离线下载
    w
    msdn帮助,离线下载
    vs2013 找不到帮助 help查看器
    vs2013 找不到帮助 help查看器
    c# wpf 加密文本
    c# wpf 加密文本
  • 原文地址:https://www.cnblogs.com/CooLLYP/p/6500602.html
Copyright © 2011-2022 走看看