How to escape Html in Angular js

Points To Remember


  • You need to use SCE to render html as it is on the page.
  • There are two ways to use sce either you use it in the angular controller to prevent escape html or you can create a filter to do this where ever you need it.
  • Using it with a filter is a much better way to do so, if you need to do it at multiple places.

Following Plunker example shows how you can prevent escaping of Html




Prevent Escape Html from angularjs Controllers

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</head>

<body ng-app="demo">
<div ng-controller="home">
  Original Text : {{text}}<br/><br /><br />
  EscapedText   : <span ng-bind-html="text"></span>

</div>

<script>
var app = angular.module("demo",[]);

app.controller('home', function ($scope, $sce) {
    $scope.text = $sce.trustAsHtml("hi this is a <b>demo text</b> <br> <a href='#'>This is a link</a>");
});


</script>

</body>
</html>

Using this method you can prevent escape any value and display it as html.

Prevent Escaping Html using angularjs Filter

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</head>

<body ng-app="demo">
<div ng-controller="home">
  Original Text : {{text}}<br/><br /><br />
  EscapedText   : <span ng-bind-html="text | escapeHtml"></span>

</div>

<script>
var app = angular.module("demo",[]);

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

app.controller('home', function ($scope) {
    $scope.text = "hi this is a <b>demo text</b> <br> <a href='#'>This is a link</a> ";
});


</script>

</body>
</html>

The above code will give the following output.

Using this method you can show the render the html using the filter escapeHtml wherever needed. 

No comments:

Powered by Blogger.