zoukankan      html  css  js  c++  java
  • 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="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
    ‘ +<em onclick="this.textContent=‘code_bunny‘">click here</em>
    ‘ +
        ‘snippet</p>‘;
        $scope.trustHtml = $sce.trustAsHtml($scope.myHtml)
    });

    这样,在div内就能加载上带有html标签的内容,标签的属性以及绑定在元素上的事件都会被保留。

  • 相关阅读:
    【渗透测试】hydra使用小结
    Git/SQL/正则表达式的在线练习平台
    加密算法的前世今生
    Linux的进程、线程、文件描述符是什么
    一文看懂 session 和 cookie
    Linux 文件目录都是什么鬼?
    Linux shell 的实用小技巧
    关于 Linux shell 你必须知道的
    我用四个命令概括了 Git 的所有套路
    如何寻找最长回文子串
  • 原文地址:https://www.cnblogs.com/wwlhome/p/5772462.html
Copyright © 2011-2022 走看看