Open In App

How to use AngularJS to Display HTML content value ?

Improve
Improve
Like Article
Like
Save
Share
Report

The ng-bind-html Directive is used to bind the innerHTML of an HTML element to application data and remove dangerous code from the HTML string. The $sanitize service is a must for the ng-bind-html directive. It is supported by all HTML elements. 

Syntax:

<element ng-bind-html="expression"> 
    Contents... 
</element>

Approach:

  • Initialize the libraries that we are using. Here, we are mainly using the angular-sanitize.js library.
  • Create an app and its controller scope.
  • Define the controller variable.
  • Call the app and controller to the body of HTML.
  • Inside the body use span tag and use attribute ng-bind-html and assign the value as the scope variable.

Example 1: This example illustrates the rendering of the HTML content values using AngularJS.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
    <title>Displaying HTML content value in AngularJS</title>
    <script src=
            charset="utf-8">
    </script>
    <script src=
            charset="utf-8">
    </script>
</head>
  
<body ng-app="myApp" 
      ng-controller="myCtrl"
      <span ng-bind-html="message"></span>
    <script type="text/javascript">
        var app = angular.module('myApp', ['ngSanitize']);
        app.controller('myCtrl', function($scope) {
            $scope.message = '<h1>GeeksforGeeks</h1>';
        });
    </script>
</body>
</html>


Output:

Example 2: This example illustrates the implementation of the ng-bind-html directive to display the HTML content value using AngularJS. 

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>
        Displaying HTML content value in AngularJS
    </title>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">
    </script>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-sanitize.min.js">
    </script>
    <style>
        .green {
            border: 2px dashed red;
            border-radius: 50px;
            color: green;
            font-weight: bold;
            font-size: 25px;
            font-family: 'Arial';
        }
    </style>
</head>
  
<body ng-controller="geek" style="text-align: center">
    <h1 style="color: green">GeeksforGeeks</h1>
    <h3>Displaying HTML content value in AngularJS</h3>
    <p ng-bind-html="text"></p>
  
    <script>
        var myApp = angular.module('myApp', ['ngSanitize']);
        myApp.controller('geek', ['$scope',
            function($scope) {
                $scope.text = 
    "<p class ='green'> GeeksforGeeks Learning Together</p>";
            },
        ]);
    </script>
</body>
</html>


Output:

 



Last Updated : 05 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads