Open In App

How to insert HTML into view from AngularJS controller?

The ng-bind-html directive is a secure way of binding content to an HTML element. So in order to insert HTML into view, we use the respective directive.

While using AngularJS, write HTML in our corresponding application, we should check the HTML for dangerous or error prone code. By including the “angular-sanitize.js” module in the application we can do so by running the HTML code through the ngSanitize function.



Syntax:

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

ngSanitize:
It constitutes of 2 steps:



Parameters:

Example 1:




<html>
<script src=
  </script>
<script src=
  </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 = "GeeksForGeeks: <h1>Hello!</h1>";
        });
    </script>
  
    <p><b>Note:</b> This example includes the "angular-sanitize.js",
      which has functions for removing potentially 
      dangerous tokens from the HTML.</p>
  
</body>
  
</html>

Output:

Example 2:




<!DOCTYPE html> 
<html ng-app="myApp"
  
<head
    <title>ng-bind-html Directive</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 { 
            color: green; 
            font-size: 20px; 
        
    </style
</head
  
<body ng-controller="geek" style="text-align:center"
      
    <h1 style="color:green;">GeeksforGeeks</h1
    <h2 style="">ng-bind-html Directive</h2
      
    <p ng-bind-html="text"></p
      
    <script
        var myApp = angular.module("myApp", ['ngSanitize']); 
          
        myApp.controller("geek", ["$scope", function($scope) { 
            $scope.text = 
            "<span class='green'> GeeksforGeeks</span> is the" 
            + " computer science portal for geeks."; 
        }]); 
    </script
</body
  
</html>         

Output:


Article Tags :