关闭Angularjs对HTML标签自动转义

本文介绍如何在AngularJS中正确处理含有HTML标签的字符串,通过使用$sce.trustAsHtml方法使data-ng-bind-html生效,避免转义问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当Angular绑定的字符串中含有HTML标签的时候,其中碰到 AngularJS 获取的是一段 HTML 文本,如果直接使用 data-ng-bind 的话是被转义过的,使用 data-ng-bind-html 则可以取消转义。但是直接使用 data-ng-bind-html 的话会提示错误。

Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.

HTML 片段需要先使用 $sce.trustAsHtml(html_in_string) 将标记为信任,然后才可以使用 data-ng-bind-html="html_in_string" 取消转义。

angular.module('myApp',[])
        .controller('orderDetailController',function($scope,$http,$location,$timeout,$sce){
            AngularAction($scope,$http,$location,$timeout,$sce);
        });
function AngularAction($scope,$http,$location,$timeout,$sce){
	$scope.comment = $sce.trustAsHtml($scope.pricelist.comment);
}



HTML代码如下
 <p style="line-height:2;display: inline">
     <span data-ng-bind-html ="comment"></span>
 </p>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值