如何在angularjs中渲染html之前阻止脚本标记注入/加载?

时间:2016-07-27 18:22:10

标签: angularjs

var testApp = angular.module('testApp',['ngSanitize']);
testApp.controller('TestController',function($scope,$sce){
	$scope.htmlString = "<span>Test HTML</span><script>alert('Hello Script');</script>";
	$scope.toTrusted = function(htmlContent) {
		if(htmlContent && htmlContent != "") {
			return $sce.trustAsHtml(htmlContent);			
		}
		return "";
	};
});
<html ng-app="testApp">
<body ng-controller="TestController">
	<div ng-bind-html="toTrusted(htmlString)"></div>
	<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-sanitize.min.js"></script>
	<script type="text/javascript" src="resources/js/controllers/testController.js"></script>
</body>
</html>

我使用ng-bind-html将字符串渲染为html。有时我在html字符串中获取脚本标记,我不想注入/加载脚本标记。所以我该怎么做才能阻止脚本标记。< / p>

我也搜索过这个问题的解决方案,有人说只是在渲染html之前从字符串中删除脚本标记。所以有人建议我。有什么更好的方法呢?

我正在使用angularjs和firebase开发聊天应用程序。为了呈现聊天消息我使用ng-bind-html指令。我注意到,如果用户发送脚本标记作为聊天消息的一部分但是给定脚本正在run.So我想限制这个脚本运行。

1 个答案:

答案 0 :(得分:0)

如果您使用$ sce.trustAsHtml,则需要单独使用ng-bind。

<div ng-bind="toTrusted(htmlString)"></div>

试试这个并告诉我。