angularjs html 转义

angularjs html 转义

默认情况下,AngularJS对会对插值指令求职表达式(模型)中的任何HTML标记都进行转义,例如以下模型: 
$scope.msg = “hello,<b>world</b>!” 
<p>{{msg}}</p> 
渲染过程会对b标签进行转义,他们会议纯文本显示而非标记; 
插值指令会对模型中任意html内容进行转义,这是为了防止html注入攻击。 
如果因为某种理由,包含html标记的模型要被浏览器求职和渲染,那么可以用ng-bind-html-unsafe指令来关掉默认的html标签转义: 
<p ng-bind-html-unsafe=”msg”></p>;

使用ng-bind-html-unsafe指令需要极度小心,它应被限制在你完全信任并控制的html标签。

angularjs还有一个指令,ng-bind-html,它能够选择性净化制定html标签,同时允许其他标签被浏览器所解释,用法如下:

方法一: 
1.导入angular-sanitize.js 
2.在你app中报刊需要依赖的模块,如下:

 var app = angular.module('myApp', ['ngSanitize']);

3.<p ng-bind-html=”msg”></p>;

方法二: 
1. 导入angular-sanitize.js 
2. 将其作为一个过滤器:

angular.module('myApp')
    .filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }]);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.<p ng-bind-html=”msg | to_trusted”></p>;

转载来源:http://m.blog.csdn.net/u010552788/article/details/50924994

注意: 第二种实现方式,在angularjs 的controll中导入 to_trusted。

原文地址:https://www.cnblogs.com/Blogs-Wang/p/7524773.html