【发布时间】:2014-02-09 11:35:21
【问题描述】:
例如,如果我这样做:
var = "<a>Asd</a>";
<span>{{ var }}</span>
字符串打印为文本而不是html,那么如何打印html?
【问题讨论】:
标签: javascript html angularjs text
例如,如果我这样做:
var = "<a>Asd</a>";
<span>{{ var }}</span>
字符串打印为文本而不是html,那么如何打印html?
【问题讨论】:
标签: javascript html angularjs text
您应该使用ng-bind-html directive。
创建一个绑定,该绑定将 innerHTML 的评估结果 以安全的方式表达到当前元素中。
<ANY ng-bind-html="{expression}">
...
</ANY>
【讨论】:
var htmlString='<somehtml />',那么它应该是<span ng-bind-html='htmlString'></span>
在使用 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>
【讨论】:
你也可以试试这样的:
app.filter('to_trusted', ['$sce', function($sce) { 返回函数(文本){ 返回 $sce.trustAsHtml(text); }; }]);然后,在视图中:
ng-bind-html="myHTML | to_trusted"【讨论】: