How To Bind HTML In Angular

In this post, we will learn how to bind HTML elements in Angular.js. Here, I have added the full source code for this. First, we need to add two JS files - angular.js and angular-sanitize for binding the HTML. For this example, we have created the HTML page and added the below source code for displaying HTML in the p tag. 

First, we need to add the JavaScript file for accessing the AngularJS function.

  1. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>  
  2. <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-sanitize.js"></script>  

Write the below code for displaying HTML in p tag.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-sanitize.js"></script>  
  5.   
  6. <body>  
  7.     <div ng-app="myApp" ng-controller="myCtrl">  
  8.         <p ng-bind-html="Text"></p>  
  9.     </div>  
  10.     <script>  
  11.         var app = angular.module("myApp", ['ngSanitize']);  
  12.         app.controller("myCtrl"function($scope) {  
  13.             $scope.Text = "<h1>Display HTML in H1 tag</h1>";  
  14.         });  
  15.     </script>  
  16. </body>  
  17.   
  18. </html>  

The above code displays h1 tag inside p tag using ng-bind-html.