AngularJS ng-bind-html指令

AngularJS ng-bind-html指令

AngularJS中的ng-bind-html指令用于将HTML元素的innerHTML与应用数据绑定,并从HTML字符串中删除危险代码。$sanitize服务是ng-bind-html指令的必备条件。它被所有的HTML元素所支持。

语法:

<element ng-bind-html="expression">
    Contents... 
</element>

参数植:

  • expression:它指定了要被评估的变量或表达式。

例子1:这个例子说明了AngularJS的ng-bind-html指令。

<!DOCTYPE html>
<html>
  
<head>
    <title>ng-bind-html Directive</title>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">
    </script>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-sanitize.min.js">
    </script>
  
    <style>
        .green {
            color: green;
            font-size: 20px;
        }
    </style>
</head>
  
<body ng-app="myApp" 
      ng-controller="geek" 
      style="text-align:center">
  
    <h1 style="color:green;">GeeksforGeeks</h1>
    <h3>ng-bind-html Directive</h3>
    <p ng-bind-html="text"></p>
  
  
    <script>
        var myApp = angular.module("myApp", ['ngSanitize']);
        myApp.controller("geek", ["scope", function (scope) {
            $scope.text =
                "<span class='green'> GeeksforGeeks</span> is the"
                + " computer science portal for geeks.";
        }]);
    </script>
</body>
</html>

输出:

AngularJS ng-bind-html指令

示例2:这是另一个例子,说明了AngularJS中ng-bind-html指令的实现。

<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>ng-bind-html Directive</title>
  
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">
    </script>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-sanitize.min.js">
    </script>
  
    <style>
        .green {
            border: 2px dashed red;
            border-radius: 50px;
            color: green;
            font-weight: bold;
            font-size: 25px;
            font-family: 'Arial';
        }
    </style>
</head>
  
<body ng-controller="geek" style="text-align: center">
    <h1 style="color: green">GeeksforGeeks</h1>
    <h3>ng-bind-html Directive</h3>
    <p ng-bind-html="text"></p>
  
  
    <script>
        var myApp = angular.module('myApp', ['ngSanitize']);
        myApp.controller('geek', [
            'scope',
            function (scope) {
                $scope.text =
"<p class ='green'> GeeksforGeeks Learning Together</p>";
            },
        ]);
    </script>
</body>
</html>

输出:

AngularJS ng-bind-html指令

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程