Skip to content Skip to sidebar Skip to footer

How To Print Html String As Html

If just for example I do: var = 'Asd'; {{ var }} The string is printed like text and not as html, so how do I print the html ?

Solution 1:

You should be using ng-bind-html directive.

Creates a binding that will innerHTML the result of evaluating the expression into the current element in a secure way.

<ANYng-bind-html="{expression}">
   ...
</ANY>

Solution 2:

Before using the ng-bind-html directive you must include the $sanitize service or it will throw an error.

Error: $sce:unsafe Require a safe/trusted value Attempting to use an unsafe value in a safe context.

Error: [$sce:unsafe] http://errors.angularjs.org/1.4.5/$sce/unsafe
    at Error (native)

The right way:

<script src="angular.js"></script>
<scriptsrc="angular-sanitize.js"></script>
varmyApp= angular.module('app', ['ngSanitize']);
myApp.controller('MyController', ['$scope', function($scope) {
  $scope.myHTML = '<a href="#">Hello, World!</a>';
}]);
<divng-controller="MyController"><png-bind-html="myHTML"></p></div>

https://docs.angularjs.org/api/ngSanitize

https://docs.angularjs.org/api/ng/directive/ngBindHtml

Solution 3:

You can also try something like that:

    app.filter('to_trusted', ['$sce', function($sce) {
      return function(text) {
        return $sce.trustAsHtml(text);
      };
    }]);

and then, in view:

    ng-bind-html=" myHTML | to_trusted"

Post a Comment for "How To Print Html String As Html"