1

I have the following variable:

$scope.someVar= "Some<br>text<br>here";

When I call it in the HTML document with {{ someVar }} I get the following output:

Some<br>text<br>here

I would like the following output:

Some
text
here

What can I do so the HTML code is rendered?

Thank you in advance for all suggestions.

2
  • 4
    use ng-bind-html from ngSanitize module. You can also $compile it from a directive Commented Apr 25, 2018 at 9:51
  • Hi @AlekseySolovey , thanks for your reply. I just started angularjs. Not sure how to use that, but if I am not mistaken I need to do that the following way: <span ng-bind-html="someVar"></span>. Can I apply it somehow with the {{someVar}} code? Commented Apr 25, 2018 at 10:03

2 Answers 2

3

You can use ng-bind-html

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "My name is: <h3>John Doe</h3>";
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-sanitize.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

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

</div>

</body>
</html>

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you @VipulSolanki It worked. Is it any way possible to use ng-bind-html when calling the variable between the brackets ({{someVar}})? or do I have to use an HTML tag?
like this <p>(<ng-bind-html ng-bind-html="myText"></ng-bind-html>)</p> ? or do you want to use this variable in function?
I have it like this: <p>{{ varOne }} {{ varTwo }} <span ng-bind-html="varThree"></span></p> at the moment, and would like to have <p>{{ varOne}} {{ varTwo }} {{ varThree }}</p>. If that is possible. varOne and varTwo work fine as they have no HTML tags.
Yes, you can. if varOne or varTwo has possibly html value or not, you can use like <p><span ng-bind-html="varOne"></span> <span ng-bind-html="varTwo"></span> <span ng-bind-html="varThree"></span></p>. if variable has html code it converted otherwise it'll return actual value.
1

Other solution :
you can use $sce,
example :
html:

<div ng-app="testApp" ng-controller="testController">
    <p ng-bind-html="someVar"></p>
</div>

js:

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

app.controller('testController', ['$sce', '$scope', function($sce, $scope) {

    $scope.someVar =  $sce.trustAsHtml("Some<br>text<br>here");
}]);

Comments

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.