ng-bind-html-unsafe
was removed in Angular 1.2
I\'m trying to implement something where I need to use ng-bind-html-unsafe
. In the docs and
var line = "<label onclick="alert(1)">aaa</label>";
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
using (html):
<span ng-bind-html="line | unsafe"></span>
==>click `aaa` show alert box
include angular-sanitize.js
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
add ngSanitize
in root angular app
var app = angular.module("app", ["ngSanitize"]);
using (html):
<span ng-bind-html="line"></span>
==>click `aaa` nothing happen
$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>
For Rails (at least in my case) if you are using the angularjs-rails gem, please remember to add the sanitize module
//= require angular
//= require angular-sanitize
And then load it up in your app...
var myDummyApp = angular.module('myDummyApp', ['ngSanitize']);
Then you can do the following:
On the template:
%span{"ng-bind-html"=>"phone_with_break(x)"}
And eventually:
$scope.phone_with_break = function (x) {
if (x.phone != "") {
return x.phone + "<br>";
}
return '';
}
Personally I sanitize all my data with some PHP libraries before going into the database so there's no need for another XSS filter for me.
From 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 || '');
});
}
}]);
To use:
<div ng-bind-html-unsafe="group.description"></div>
To disable $sce
:
app.config(['$sceProvider', function($sceProvider) {
$sceProvider.enabled(false);
}]);
That should be:
<div ng-bind-html="trustedHtml"></div>
plus in your controller:
$scope.html = '<ul><li>render me please</li></ul>';
$scope.trustedHtml = $sce.trustAsHtml($scope.html);
instead of old syntax, where you could reference $scope.html
variable directly:
<div ng-bind-html-unsafe="html"></div>
As several commenters pointed out, $sce
has to be injected in the controller, otherwise you will get $sce undefined
error.
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', ['$sce', function($sce) {
// ... [your code]
}]);
Filter
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
Usage
<ANY ng-bind-html="value | unsafe"></ANY>