angularJS1笔记-(17)-ng-bind-html指令

angular不推荐大家在绑定数据的时候绑定html,但是如果你非要这么干也并不是不可以的。举个例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>指令</title>

</head>
<body ng-app ng-init="username='<h1>shit</h1>'">
<!--ng-bind指令在绑定的值包含html时会转义,为了安全(跨站脚本攻击)-->
<strong ng-bind-html="username"></strong>

<script src="app/bower_components/angular/angular.js"></script>

</body>
</html>

  写这样的一段代码在浏览器运行:

      会看到错误信息:

  看意思是在一个安全的环境中使用了不安全的值导致的,这个时候我们需要引入angular的一个依赖包 angular-sanitize:

引入完成后我们导入项目,然后在模块中写明依赖:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>指令</title>

</head>
<body ng-app="myApp" ng-init="username='<h1>shit</h1>'">
<!--ng-bind指令在绑定的值包含html时会转义,为了安全(跨站脚本攻击)-->
<strong ng-bind-html="username"></strong>

<script src="app/bower_components/angular/angular.js"></script>
<script src="app/bower_components/angular-sanitize/angular-sanitize.js"></script>
<script>
    //使用自定义的模块才可以依赖别的包里面定义模块 angular定义的默认模块没有任何依赖
    angular.module('myApp', ['ngSanitize'])
</script>
</body>
</html>

  此时运行就可以看到正确结果ngSanitize的作用是让html不转义:

原文地址:https://www.cnblogs.com/yk123/p/6953338.html