ng-bind-html-unsafe 已在Angular 1.2中删除
我正在尝试实现我需要使用的东西ng-bind-html-unsafe.在文档和github提交中,他们说:
当绑定到$ sce.trustAsHtml(string)的结果时,ng-bind-html提供ng-html-bind-unsafe like行为(innerHTML是没有清理的结果).
你怎么做到这一点?
Chr*_*ris 629
过滤
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
Run Code Online (Sandbox Code Playgroud)
用法
<ANY ng-bind-html="value | unsafe"></ANY>
Run Code Online (Sandbox Code Playgroud)
Nen*_*nad 241
那应该是:
<div ng-bind-html="trustedHtml"></div>
Run Code Online (Sandbox Code Playgroud)
加上你的控制器:
$scope.html = '<ul><li>render me please</li></ul>';
$scope.trustedHtml = $sce.trustAsHtml($scope.html);
Run Code Online (Sandbox Code Playgroud)
而不是旧语法,您可以$scope.html直接引用变量:
<div ng-bind-html-unsafe="html"></div>
Run Code Online (Sandbox Code Playgroud)
正如几位评论者指出的那样,$sce必须在控制器中注入,否则会$sce undefined出错.
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$sce', function($sce) {
// ... [your code]
}]);
Run Code Online (Sandbox Code Playgroud)
Mic*_*ins 16
我个人在进入数据库之前使用一些PHP库清理所有数据,因此不需要为我提供另一个XSS过滤器.
来自AngularJS 1.0.8
directives.directive('ngBindHtmlUnsafe', [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
}
}]);
Run Code Online (Sandbox Code Playgroud)
使用:
<div ng-bind-html-unsafe="group.description"></div>
Run Code Online (Sandbox Code Playgroud)
要禁用$sce:
app.config(['$sceProvider', function($sceProvider) {
$sceProvider.enabled(false);
}]);
Run Code Online (Sandbox Code Playgroud)
var line = "<label onclick="alert(1)">aaa</label>";
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
Run Code Online (Sandbox Code Playgroud)
使用(html):
<span ng-bind-html="line | unsafe"></span>
==>click `aaa` show alert box
Run Code Online (Sandbox Code Playgroud)
包括 angular-sanitize.js
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
Run Code Online (Sandbox Code Playgroud)
添加ngSanitizeroot角应用程序
var app = angular.module("app", ["ngSanitize"]);
Run Code Online (Sandbox Code Playgroud)
使用(html):
<span ng-bind-html="line"></span>
==>click `aaa` nothing happen
Run Code Online (Sandbox Code Playgroud)
只需创建过滤器就可以解决问题。(为Angular 1.6提供了答案)
.filter('trustHtml', [
'$sce',
function($sce) {
return function(value) {
return $sce.trustAs('html', value);
}
}
]);
Run Code Online (Sandbox Code Playgroud)
并在html中使用它,如下所示。
<h2 ng-bind-html="someScopeValue | trustHtml"></h2>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
218756 次 |
| 最近记录: |