这篇文章给大家介绍AngularJS中ng-bind-html指令的功能是什么,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
创新互联建站是一家集网站建设,华阴企业网站建设,华阴品牌网站建设,网站定制,华阴网站建设报价,网络营销,网络优化,华阴网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
前言
在为html标签绑定数据的时,如果绑定的内容是纯文本,你可以使用{{}}或者ng-bind。但在为html标签绑定带html标签的内容的时候,angularjs为了安全考虑,不会将其渲染成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> angular.module("myapp", []).controller("MyController", function ($scope) { $scope.content = "<h2>Hello world.</h2>"; $scope.txt = "Hello txt world"; }); </script> </head> <body ng-app="myapp"> <div ng-controller="MyController"> {{content}} <div ng-bind="content"></div> </div> </body> </html>
输出
ng-bind-html指令
<div ng-bind-html="content"></div>
这时就会出现安全的错误,如图:
但可以通过引入下面的模块,自动检测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 = "<h2>Hello world.</h2>"; $scope.txt = "Hello txt world"; }); </script>
这时刷新预览
所以
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.
另外一种处理方式
通过自定义过滤器,将带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 = "<h2>Hello world.</h2>"; $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>
关于AngularJS中ng-bind-html指令的功能是什么就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
文章名称:AngularJS中ng-bind-html指令的功能是什么
标题来源:https://www.cdcxhl.com/article20/gcpojo.html
成都网站建设公司_创新互联,为您提供服务器托管、微信小程序、关键词优化、微信公众号、软件开发、标签优化
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联