Search code examples
javascriptangularjsngsanitize

How to safely bind HTML from Model to View


Show html code as html code if all text and styles are saved on api

Let's say i'm using a text editor and i save on an api not only the text, but the html styles too (ex. <align>, <h1>, blabla). What i want is to show the text on my html view, but using the styles. Per example, if i've saved <h1><u>Hello there!</u><h1>, i need to show on my html view the text as title h1 and underlined.

My code to get the api response:

function info(){
        $http.get('/theApi')
        .then(function(data){
            $scope.product = data.data.Response;
        });
    }

Returns something like this:

[{Name: "Chuck", Message: "<h1><u>Hello there!</u><h1>"}]

If i pass the data like this:

{{product.Message}}

On my html view i'll get, literally:

<h1><u>Hello there!</u><h1>

So, what can i do to get the text as a title h1 and undderlined on the html view?

I'm using AnguarJs and Javascript.

Thanx in advance.


Solution

  • Use the ng-bind-html directive with the ngSanitize module:

    angular.module('bindHtmlExample', ['ngSanitize'])
    .controller('ExampleController', ['$scope', function($scope) {
        $scope.myHTML =
           '<h1><u>Hello there!</u><h1>';
     }]);
    <script src="//unpkg.com/angular/angular.js"></script>
    <script src="//unpkg.com/angular-sanitize/angular-sanitize.js"></script>
    
    <body ng-app="bindHtmlExample" ng-controller="ExampleController">
      <input ng-model="myHTML">
      <p ng-bind-html="myHTML"></p>
    </body>

    For more information, AngularJS ng-bind-html Directive API Reference.