ng-bind-html-unsafe在Angular 1.2中被移除
我试图实现的东西,我需要使用ng-bind-html-不安全。在文档和github提交中,他们说:
ng-bind-html提供了ng-html-bind-不安全的行为(innerHTML的结果没有 当绑定到$sce.trustAsHtml(string)的结果时,sanitization)。
怎么做呢?
ng-bind-html-unsafe在Angular 1.2中被移除
我试图实现的东西,我需要使用ng-bind-html-不安全。在文档和github提交中,他们说:
ng-bind-html提供了ng-html-bind-不安全的行为(innerHTML的结果没有 当绑定到$sce.trustAsHtml(string)的结果时,sanitization)。
怎么做呢?
当前回答
$scope.trustAsHtml=function(scope)
{
return $sce.trustAsHtml(scope);
}
<p class="card-text w-100" ng-bind-html="trustAsHtml(note.redoq_csd_product_lead_note)"></p>
其他回答
这应该是:
<div ng-bind-html="trustedHtml"></div>
在你的控制器中:
$scope.html = '<ul><li>render me please</li></ul>';
$scope.trustedHtml = $sce.trustAsHtml($scope.html);
而不是旧的语法,你可以直接引用$scope.html变量:
<div ng-bind-html-unsafe="html"></div>
正如一些评论者指出的那样,$sce必须注入到控制器中,否则将得到$sce undefined错误。
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$sce', function($sce) {
// ... [your code]
}]);
JavaScript
$scope.get_pre = function(x) {
return $sce.trustAsHtml(x);
};
HTML
<pre ng-bind-html="get_pre(html)"></pre>
就我个人而言,在进入数据库之前,我会用一些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 || '');
});
}
}]);
使用方法:
<div ng-bind-html-unsafe="group.description"></div>
禁用$sce:
app.config(['$sceProvider', function($sceProvider) {
$sceProvider.enabled(false);
}]);
简单地创建一个过滤器就可以了。(适用于Angular 1.6)
.filter('trustHtml', [
'$sce',
function($sce) {
return function(value) {
return $sce.trustAs('html', value);
}
}
]);
并在html中按如下方式使用。
<h2 ng-bind-html="someScopeValue | trustHtml"></h2>
对于Rails(至少在我的情况下),如果你正在使用angularjs-rails gem,请记得添加sanitize模块
//= require angular
//= require angular-sanitize
然后在你的应用程序中加载它…
var myDummyApp = angular.module('myDummyApp', ['ngSanitize']);
然后您可以执行以下操作:
在模板中:
%span{"ng-bind-html"=>"phone_with_break(x)"}
最后:
$scope.phone_with_break = function (x) {
if (x.phone != "") {
return x.phone + "<br>";
}
return '';
}