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标签的内容,标签的属性以及绑定在元素上的事件都会被保留。

  • 相关阅读:
    window 编译lua 5.3
    邮件服务器软件
    mkyaffs2image 生成不了120M的镜像文件的解决方法
    C static struct
    uboot 如何向内核传递参数
    linux 链接理解
    snmp 协议之理解
    交叉编译知识点总结
    回滚原理 Since database connections are thread-local, this is thread-safe.
    REST 架构的替代方案 为什么说GraphQL是API的未来?
  • 原文地址:https://www.cnblogs.com/wwlhome/p/5772462.html
Copyright © 2011-2022 走看看