如何将html字符串打印为html

its*_*sme 27 html javascript text angularjs

如果只是例如我做:

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

<span>{{ var }}</span>
Run Code Online (Sandbox Code Playgroud)

字符串打印得像文本而不是html,所以如何打印html?

Flo*_* F. 42

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

创建一个绑定,将innerHTML以安全的方式将表达式计算到当前元素中.

<ANY ng-bind-html="{expression}">
   ...
</ANY>
Run Code Online (Sandbox Code Playgroud)

  • 现在你需要引用ng-sanitize来实现这一目标.https://docs.angularjs.org/api/ngSanitize (3认同)

Wel*_*ndo 10

在使用ng-bind-html指令之前,必须包含$ sanitize服务,否则将引发错误.

错误:$ sce:unsafe需要安全/可信值尝试在安全上下文中使用不安全值.

Error: [$sce:unsafe] http://errors.angularjs.org/1.4.5/$sce/unsafe
    at Error (native)
Run Code Online (Sandbox Code Playgroud)

正确的方式:

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

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

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


Ada*_*ala 6

你也可以尝试这样的事情:


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

然后,在视图中:


    ng-bind-html=" myHTML | to_trusted"