源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

深入理解AngularJS中的ng-bind-html指令

  • 时间:2021-10-27 17:20 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:深入理解AngularJS中的ng-bind-html指令
[b]前言[/b] 在为html标签绑定数据的时,如果绑定的内容是纯文本,你可以使用{{}}或者ng-bind。但在为html标签绑定带html标签的内容的时候,angularjs为了安全考虑,不会将其渲染成html,而是将其当做文本直接在页面上展示。 [b]先来看一个例子[/b]
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title></title>
 <script src="js/angular.min.js"></script>
 <script>
 angular.module("myapp", []).controller("MyController", function ($scope) {
 $scope.content = "<h1>Hello world.</h1>";
 $scope.txt = "Hello txt world";
 });
 </script>
</head>
<body ng-app="myapp">
 <div ng-controller="MyController">
 {{content}}
 <div ng-bind="content"></div> 
 </div>
</body>
</html>
输出 [img]http://files.jb51.net/file_images/article/201703/2017327102533079.png?2017227102542[/img] [b]ng-bind-html指令[/b]
 <div ng-bind-html="content"></div>
这时就会出现安全的错误,如图: [img]http://files.jb51.net/file_images/article/201703/2017327102631831.png?2017227102639[/img] 但可以通过引入下面的模块,自动检测html的内容是否安全
 <script src="http://apps.bdimg.com/libs/angular.js/1.5.0-beta.0/angular-sanitize.min.js"></script>

 <script>
 angular.module("myapp", ["ngSanitize"]).controller("MyController", function ($scope) {
 $scope.content = "<h1>Hello world.</h1>";
 $scope.txt = "Hello txt world";
 });
 </script>
这时刷新预览 [img]http://files.jb51.net/file_images/article/201703/2017327102703170.png?2017227102713[/img] [b]所以[/b] ng-bind-html 指令是通一个安全的方式将内容绑定到 HTML 元素上。 当你想让 AngularJS 在你的应用中写入 HTML,你就需要去检测一些危险代码。通过在应用中引入 "angular-santize.js" 模块,使用 ngSanitize 函数来检测代码的安全性。 in your application you can do so by running the HTML code through the ngSanitize function. [b]另外一种处理方式[/b] 通过自定义过滤器,将带html标签的内容都当成安全的进行处理。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title></title>
 <script src="js/angular.min.js"></script>
 <!--<script src="http://apps.bdimg.com/libs/angular.js/1.5.0-beta.0/angular-sanitize.min.js"></script>-->
 <script>
 angular.module("myapp", []).controller("MyController", function ($scope) {
  $scope.content = "<h1>Hello world.</h1>";
  $scope.txt = "Hello txt world";
 }).filter("safeHtml", function ($sce) {
  return function (input) {
  //在这里可以对加载html渲染后进行特别处理。
  return $sce.trustAsHtml(input);
  };
 });
 </script>
</head>
<body ng-app="myapp">
 <div ng-controller="MyController">
 {{content}}
 <div ng-bind="content"></div> 
 <!--<div ng-bind-html="content"></div>-->
 <div ng-bind-html="content|safeHtml"></div>
 </div>
</body>
</html>
[b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部