29

If just for example I do:

var = "<a>Asd</a>";

<span>{{ var }}</span>

The string is printed like text and not as html, so how do I print the html ?

0

3 Answers 3

42

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.

<ANY ng-bind-html="{expression}">
   ...
</ANY>
Sign up to request clarification or add additional context in comments.

2 Comments

expression can be variable or function. lets consider var htmlString='<somehtml />', then it should be <span ng-bind-html='htmlString'></span>
now you need to reference ng-sanitize to accomplish this. docs.angularjs.org/api/ngSanitize
10

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>
<script src="angular-sanitize.js"></script>
var myApp = angular.module('app', ['ngSanitize']);
myApp.controller('MyController', ['$scope', function($scope) {
  $scope.myHTML = '<a href="#">Hello, World!</a>';
}]);
<div ng-controller="MyController">
 <p ng-bind-html="myHTML"></p>
</div>

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

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

Comments

6

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"

1 Comment

Where is this added in the angular project?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.