首页  >  文章  >  web前端  >  深入理解AngularJS中的ng-bind-html指令的图文代码详解

深入理解AngularJS中的ng-bind-html指令的图文代码详解

黄舟
黄舟原创
2017-03-28 14:58:071179浏览

ng-bind-html和ng-bind的区别就是,ng-bind把值作为字符串,和元素的内容进行绑定,但是ng-bind-html把值作为html,和元素的html进行绑定.相当于jq里面的.text()和.html()。这篇文章主要给大家深入的介绍了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 = "<h1>Hello world.</h1>";
 $scope.txt = "Hello txt world";
 });
 </script>
</head>
<body ng-app="myapp">
 <p ng-controller="MyController">
 {{content}}
 <p ng-bind="content"></p> 
 </p>
</body>
</html>

输出

深入理解AngularJS中的ng-bind-html指令的图文代码详解

ng-bind-html指令

 <p ng-bind-html="content"></p>

这时就会出现安全的错误,如图:

深入理解AngularJS中的ng-bind-html指令的图文代码详解

但可以通过引入下面的模块,自动检测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>

这时刷新预览

深入理解AngularJS中的ng-bind-html指令的图文代码详解

所以

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 = "<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">
 <p ng-controller="MyController">
 {{content}}
 <p ng-bind="content"></p> 
 <!--<p ng-bind-html="content"></p>-->
 <p ng-bind-html="content|safeHtml"></p>
 </p>
</body>
</html>

总结

以上是深入理解AngularJS中的ng-bind-html指令的图文代码详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn