首页 > Web开发 > 详细

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

时间:2017-06-06 20:24:29      阅读:277      评论:0      收藏:0      [点我收藏+]

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不转义:

技术分享

 

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

原文:http://www.cnblogs.com/yk123/p/6953338.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!