angularjs中ng-bind-html的用法总结
2019/6/27 20:56:54
本文主要是介绍angularjs中ng-bind-html的用法总结,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
本篇主要讲解angular中的$sanitize这个服务.此服务依赖于ngSanitize模块.(这个模块需要加载angular-sanitize.js插件)
要学习这个服务,先要了解另一个指令: ng-bing-html.
顾名思义,ng-bind-html和ng-bind的区别就是,ng-bind把值作为字符串,和元素的内容进行绑定,但是ng-bind-html把值作为html,和元素的html进行绑定.相当于jq里面的.text()和.html().
但是,出于安全考虑,如果我们直接使用ng-bind-html是会报错的,ng-bind-html后面的内容必须经过一定的处理.
处理的方式有两种,一种是使用$sce服务,另一种就是使用$sanitize服务.$sce服务怎么用,在以后的文章中会独立讲解,这篇主要讲解$sanitize服务.
$sanitize会根绝一个白名单来净化html标签.这样,不安全的内容就不会被返回. 白名单是根据$compileProvider的aHrefSanitizationWhitelist和imgSrcSanitizationWhitelist函数得到的.
看一个栗子:
html:
<!DOCTYPE html> <html ng-app="myApp"> <head> <title></title> <meta charset="utf-8"> <script src="../angular-1.3.2.js"></script> <script src="angular-sanitize.min.js"></script> <script src="script.js"></script> <link type="text/css" href="../bootstrap.css" rel="external nofollow" rel="stylesheet" /> </head> <body> <div class="container" ng-controller="ctrl"> <div ng-bind-html="trustHtml"></div> </div> </body> </html>
js:
var app =angular.module(‘myApp‘,[‘ngSanitize‘]); app.controller(‘ctrl‘,function($scope,$sce){ $scope.myHtml = ‘<p style="color:blue">an html\n‘ + ‘<em onclick="this.textContent=\‘code_bunny\‘">click here</em>\n‘ + ‘snippet</p>‘; $scope.trustHtml = $sce.trustAsHtml($scope.myHtml) });
这样,在div内就能加载上带有html标签的内容,标签的属性以及绑定在元素上的事件都会被保留。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。
这篇关于angularjs中ng-bind-html的用法总结的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist
- 2024-03-11icons for vue
- 2024-03-07breadcrumbs react js
- 2024-03-06react login page example
- 2024-03-06react router uselocation
- 2024-03-04postgres jsonb_set