如何将HTML字符串打印为HTML

29

举个例子,如果我只是执行:

var = "<a>Asd</a>";

<span>{{ var }}</span>

字符串被打印为文本而不是 HTML,那么我该如何打印 HTML?

3个回答

42

你应该使用ng-bind-html指令

创建一个绑定,以安全的方式将表达式的评估结果innerHTML到当前元素中。

<ANY ng-bind-html="{expression}">
   ...
</ANY>

1
表达式可以是变量或函数。让我们考虑 var htmlString='<somehtml />',那么它应该是 <span ng-bind-html='htmlString'></span> - Fizer Khan
3
现在您需要引用 ng-sanitize 来完成此操作。https://docs.angularjs.org/api/ngSanitize - Eduardo

10
在使用 ng-bind-html 指令之前,您必须包含 $sanitize 服务,否则它会抛出一个错误。 错误:$sce:unsafe 要求一个安全/可信赖的值 试图在安全上下文中使用不安全的值。
Error: [$sce:unsafe] http://errors.angularjs.org/1.4.5/$sce/unsafe
    at Error (native)

正确的方式:

<script src="angular.js"></script>
<script src="angular-sanitize.js"></script>
var myApp = angular.module('app', ['ngSanitize']);
myApp.controller('MyController', ['$scope', function($scope) {
  $scope.myHTML = '<a href="#">Hello, World!</a>';
}]);
<div ng-controller="MyController">
 <p ng-bind-html="myHTML"></p>
</div>

https://docs.angularjs.org/api/ngSanitize

https://docs.angularjs.org/api/ng/directive/ngBindHtml


6

你也可以尝试这样做:

    app.filter('to_trusted', ['$sce', function($sce) {
      return function(text) {
        return $sce.trustAsHtml(text);
      };
    }]);

然后,在视图中:

    ng-bind-html=" myHTML | to_trusted"


这个在 Angular 项目中添加在哪里? - lesolorzanov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接