Aju John
Aju John

Reputation: 2244

Show html tags on the page with ng-bind-html

Please see below given code:

    <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 = "My name is: <h1>John Doe</h1>";
        });
    </script>

The output is: My Name is: John Doe

How can i show the text as it is. For example: My Name is : <h1>John Doe</h1> I want to show the HTML tags on the page.

Upvotes: 2

Views: 830

Answers (4)

Hamid Mohayeji
Hamid Mohayeji

Reputation: 4295

First create a filter using $sce:

app.filter("html", ['$sce', function($sce) {
  return function(input){
    return $sce.trustAsHtml(input);
  }
}]);

Then:

<div ng-bind-html="myText | html"></div>

Upvotes: 3

Vinoth
Vinoth

Reputation: 1113

I think you should use like this

in your controller

$scope.mytext="&lth1&gtJohn Doe&lt/h1&gt"

in you html page

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

Upvotes: 1

Naren Murali
Naren Murali

Reputation: 58199

Please use the $sce of angularjs.

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope, $sce) {
  $scope.myText = $sce.trustAsHtml("My name is: <h1>John Doe</h1>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<div ng-app="myApp" ng-controller='MyController'>
  <p ng-bind-html="myText"></p>
</div>

Reference:

  1. How to use $sce

Upvotes: 3

freelancer
freelancer

Reputation: 1164

Use ng-bind instead ng-bind-html

<div ng-app="myApp" ng-controller="myCtrl">        
    <p ng-bind="myText"></p>        
</div>

Or simply

<p>{{myText}}</p>

Upvotes: 2

Related Questions