如何从AngularJS控制器插入HTML到视图中
ng-bind-html指令是一种将内容绑定到HTML元素的安全方式。因此,为了在视图中插入HTML,我们使用相应的指令。
在使用AngularJS时,在我们相应的应用程序中编写HTML,我们应该检查HTML中是否有危险或容易出错的代码。通过在应用程序中包含 “angular-sanitize.js “模块,我们可以通过ngSanitize函数运行HTML代码来实现这一点。
语法:
<element ng-bind-html="expression"></element>
ngSanitize:
它包括两个步骤:
- 包括angular-sanitize.min.js资源。
<script src="lib/angular/angular-sanitize.min.js"></script>
- 在一个js文件中(控制器或通常是app.js),我们必须包括ngSanitize。
angular.module('myApp', ['myApp.filters', 'myApp.services',
'myApp.directives', 'ngSanitize'])
参数:
- expression。指定一个表达式或用于评估的值。
示例 1:
<html>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-sanitize.js">
</script>
<body>
<div ng-app="myApp"
ng-controller="myCtrl">
<p ng-bind-html="myText">
</p>
</div>
<script>
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function(scope) {
scope.myText = "GeeksForGeeks: <h1>Hello!</h1>";
});
</script>
<p><b>Note:</b> This example includes the "angular-sanitize.js",
which has functions for removing potentially
dangerous tokens from the HTML.</p>
</body>
</html>
输出:

示例 2:
<!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 {
color: green;
font-size: 20px;
}
</style>
</head>
<body ng-controller="geek" style="text-align:center">
<h1 style="color:green;">GeeksforGeeks</h1>
<h2 style="">ng-bind-html Directive</h2>
<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>
输出:

极客教程