In this tutorial, I am going to explain you about ng-bind-html directive in Angular Js. In the previous session, we have discussed ng-bind directive in Angular Js.

Introduction:

The ng-bind-html directive in angular js is used to bind the content to HTML element in a secure way. When we allow the HTML to our application. We need to make sure the HTML for the dangerous code. To prevent the HTML from dangerous code to we need to include the angular-sanitize.js library in our application. We can do by running our code through ngSanitize function.

ng-bind-html

You can find the angular-sanitize.js library at this location:
https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js
Here is the Syntax for declaring ng-bind-html:
<element ng-bind-html="expression"></element> Where

Expression:  Specifies a variable, or an expression to evaluate.

An example of ng-bind-html in Angular Js:

<!DOCTYPE html>
<html>
<title>ng-bind-html example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<p ng-bind-html="myText"></p>

</div>

<script>
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
$scope.myText = "Welcome to: <h1>Debug On Web</h1>";
});
</script>

<p><b>Note:</b> In this example i includes the "angular-sanitize.js",
which has functions for removing potentially dangerous tokens from the HTML.</p>

</body>
</html>


 

You can find the demo of this example from here

Hope you understand this tutorial about how to prevent HTML from dangerous code.

You must read my previous article:

Thank You,

Leave a Comment