How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Angularjs

Angularjs Problem Overview


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 on the github commit they say:

> ng-bind-html provides ng-html-bind-unsafe like behavior (innerHTML's the result without sanitization) when bound to the result of $sce.trustAsHtml(string).

How do you do this?

Angularjs Solutions


Solution 1 - Angularjs

Filter

app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

Usage

<ANY ng-bind-html="value | unsafe"></ANY>

Solution 2 - Angularjs

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]
 }]);

Solution 3 - Angularjs

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);
}]);

Solution 4 - Angularjs

var line = "<label onclick="alert(1)">aaa</label>";

1. use filter
app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

using (html):

<span ng-bind-html="line | unsafe"></span>
==>click `aaa` show alert box
2. use ngSanitize : safer

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

Solution 5 - Angularjs

Simply creating a filter will do the trick. (Answered for Angular 1.6)

.filter('trustHtml', [
        '$sce',
        function($sce) {
            return function(value) {
                return $sce.trustAs('html', value);
            }
        }
    ]);

And use this as follow in the html.

<h2 ng-bind-html="someScopeValue | trustHtml"></h2>

Solution 6 - Angularjs

If you want the old directive back, you can add this to your app:

Directive:

directives.directive('ngBindHtmlUnsafe', ['$sce', function($sce){
    return {
        scope: {
            ngBindHtmlUnsafe: '=',
        },
        template: "<div ng-bind-html='trustedHtml'></div>",
        link: function($scope, iElm, iAttrs, controller) {
            $scope.updateView = function() {
                $scope.trustedHtml = $sce.trustAsHtml($scope.ngBindHtmlUnsafe);
            }

            $scope.$watch('ngBindHtmlUnsafe', function(newVal, oldVal) {
                $scope.updateView(newVal);
            });
        }
    };
}]);

Usage

<div ng-bind-html-unsafe="group.description"></div>

Source - https://github.com/angular-ui/bootstrap/issues/813

Solution 7 - Angularjs

JavaScript

$scope.get_pre = function(x) {
    return $sce.trustAsHtml(x);
};

HTML

<pre ng-bind-html="get_pre(html)"></pre>

Solution 8 - Angularjs

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 '';
}

Solution 9 - Angularjs

my helpful code for others(just one aspx to do text area post)::

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication45.WebForm1" %>

<!DOCTYPE html>

    enter code here

<html ng-app="htmldoc" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
    <script src="angular-sanitize.min.js"></script>
    <script>
        angular.module('htmldoc', ['ngSanitize']).controller('x', function ($scope, $sce) {
            //$scope.htmlContent = '<script> (function () { location = \"http://moneycontrol.com\"; } )()<\/script> In last valid content';
            $scope.htmlContent = '';
            $scope.withoutSanitize = function () {
                return $sce.getTrustedHtml($scope.htmlContent);
            };
            $scope.postMessage = function () {
                var ValidContent = $sce.trustAsHtml($scope.htmlContent);

                //your ajax call here
            };
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Example to show posting valid content to server with two way binding
        <div ng-controller="x">
            <p ng-bind-html="htmlContent"></p>
            <textarea ng-model="htmlContent" ng-trim="false"></textarea>
            <button ng-click="postMessage()">Send</button>
        </div>
    </form>
</body>
</html>

Solution 10 - Angularjs

$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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontimhaakView Question on Stackoverflow
Solution 1 - AngularjsChrisView Answer on Stackoverflow
Solution 2 - AngularjsNenadView Answer on Stackoverflow
Solution 3 - AngularjsMichael J. CalkinsView Answer on Stackoverflow
Solution 4 - AngularjsnguyênView Answer on Stackoverflow
Solution 5 - AngularjsSTEELView Answer on Stackoverflow
Solution 6 - AngularjsAdrian EnriquezView Answer on Stackoverflow
Solution 7 - Angularjswcc526View Answer on Stackoverflow
Solution 8 - AngularjsSomeDudeSomewhereView Answer on Stackoverflow
Solution 9 - AngularjsSaurabhView Answer on Stackoverflow
Solution 10 - AngularjsSurya Pratim MukherjeeView Answer on Stackoverflow