angular ng-bind-html $sce.trustAsHtml

使用ng-bind-html和$sce.trustAsHtml显示有html符号的内容
 

angularjs的强大之处之一在于它的双向数据绑定的功能,我们通常会使用data-ng-bind或者data-ng-model来绑定数据。但是在项目中很多数据都带有各种各样的html标签,而angularjs绑定的数据都会默认以文本的形式输出,并不会去识别html标签,这样做主要是为了防止html标签中的注入攻击,提高了安全性。那么如何显示这些html标签呢?

主要有两种方法:

1.过滤器

<body ng-app="myApp" ng-controller="myCtl">
<div ng-bind-html="htmlContent | to_trusted">
</div>
</body>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtl',['$scope', function($scope){
        $scope.htmlContent = '<h1 style="color: orange">wednesday</h1>';
    }]);
    app.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
  };
}]);
</script>

2.$sce.trustAsHtml

<body ng-app="myApp" ng-controller="myCtl">
    <div ng-bind-html="content">
    </div>
</body>
<script>
    var app = angular.module('myApp', []);
    $scope.content="My name is: <h1>John Doe</h1>";
    app.controller('myCtl',['$scope','$sce', function($scope,$sce){
        $scope.content = $sce.trustAsHtml( $scope.content );
    }]);
</script>

这里主要有地方要注意:

1. ng-bind-html指令是通过一个安全的方式将内容绑定到HTML元素上,该属性依赖于$sanitize,需要在项目中引入angular-sanitize.js文件,并在module定义时注入该服务ngSanitize。

2.通过ng-bind-html指令绑定html元素,为什么还需要$sce?

这是因为如果在angularjs中绑定的数据有html标签时,如上面的<h1>,会被angularjs认为是不安全的而自动过滤掉,为了保留这些标签就需要开启非安全模式,这是非常危险的。$sce是angularJS自带的安全处理模块,因此需要$sce.trustAsHtml()方法将数据内容以html的形式解析并返回。

3.几种绑定方式的对比

(1)ng-bind-html和内置的$sanitize服务

$sanitize会自动对html标签进行净化,并会把标签的属性以及绑定在元素上的事件都移除,仅保留了标签和内容。

(2)ng-bind-html和$sce.trustAsHtml()

它不再经过sanitize服务的净化,直接作为元素的.html()绑定给元素,保留所有的属性和事件,这一行的内容不依赖于ngSanitize模块,$sce服务是内置的。

(3)ng-bind

绑定的值就作为字符串填充到元素里。

使用ng-bind-html容易引起XSS(脚本注入攻击),这一点一定要注意。

原文地址:https://www.cnblogs.com/lyy-2016/p/7928728.html