我正在尝试在模板中插入一个包含一些标记的字符串。
在控制器中:
$scope.message = "Hello moto <a ui-sref='home.test'>click</a>";
模板:
<div ng-bind-html="message.text"></div>它呈现为:
<div ng-bind-html="message.text" <div="" class="ng-binding">Hello moto <a>click</a></div>尝试使用以下过滤器也无济于事;对于两个注释的选项,文本都是简单转义的:
angular.module('test-filters', ['ngSanitize'])
.filter('safe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
//return $sce.trustAsUrl(val);
//return $sce.trustAsResourceUrl(val);
};
});如何在不对字符串进行转义或剥离属性的情况下插入字符串?
编辑: Plunker http://plnkr.co/edit/H4O16KgS0mWtpGRvW1Es?p=preview (使用引用ngSanitize的sylwester版本更新
发布于 2014-06-12 17:50:10
让我们看看这里,http://jsbin.com/faxopipe/1/edit,它现在已经排序了。它不起作用,因为在'ui-sref‘标记中有另一个指令,所以你必须使用$sce服务。
请在您的js中添加方法:
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);在视图中:
<p ng-bind-html="to_trusted(message)"></p>发布于 2016-07-25 22:23:17
在使用ui.router path方案中,您必须将$compile与动态html的$sce结合使用,以便ui-sref正常工作。如果你不这样做,你只会看到一个实际上不起作用的链接。
例如<span> Hello moto <a ui-sref='home.test'> Link </a> </span>
//You must need to add boundary conditions, this is just for demonstration
$scope.to_trusted = function(someHTML) {
var compiledVal = $compile(someHTML)($scope);
var compiledHTML = compiledVal[0].outerHTML;
return $sce.trustAsHtml(compiledHTML);
}你像这样使用,
<p ng-bind-html="to_trusted(message)"></p>请注意,您的消息必须是从"<"开始的有效超文本标记语言,所以如果您向$compile传递一个非超文本标记语言,您将得到jqlite错误。我用<span>来处理你的案子。
发布于 2014-06-12 16:50:44
您错过了对angular-Saniize.js的引用,您也将其注入到了angular.app中
var app = angular.module('plunker', ['ngSanitize']);绑定html中最简单的选项是ng- bind -html:
<li>link ng-html-bind <div ng-bind-html="message"></div></li>请参阅Plunkr
https://stackoverflow.com/questions/24178316
复制相似问题