Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show html in angularjs template instead of string?

Tags:

angularjs

I have a variable in my scope:

$scope.myvar = "Hello<br><br>World"

In my template I use:

<div>{{myvar}}</div>

The issue is myvar shows the literal text, whereas I want it to show the line breaks. How to do this? Note that I want to make it such that if I in the future, myvar gets updated with other HTML, then what is shown on the page should be the "compiled" html as opposed to the literal string with the html tags in it.

like image 358
Rolando Avatar asked Oct 24 '25 04:10

Rolando


1 Answers

You can use ngBindHtml for that.
Keep in mind that due to Angular's Strict Conceptual Escaping the content needs to be either sanitized (using the additonal module ngSanitize) or explicitely "trustedAsHtml" (using $sce.trustAsHtml()). The latter is supposed to be used only for content you know is safe (e.g. nothing user defined) and is not recommended anyway.

Note: ngSanitize is an non-core module and should be included separately:
<script src=".../angular.min.js"></script>
<script src=".../angular-sanitize.min.js"></script>

Examples:

/* Using ngSanitize */
angular.module('app', ['ngSanitize'])
.controller('myCtrl', function ($scope) {
    $scope.myHtml = 'Hello<br /><br />world !';
});

/* Using $sce.trustAsHtml() */
angular.module('app', [])
.controller('myCtrl', function ($sce, $scope) {
    $scope.myHtml = $sce.trustAsHtml('Hello<br /><br />world !');
});

Note that ngSanitize will filter "non-appropriate" content, while $sce.trustAsHtml will allow anything.

See, also, this short demo.

like image 157
gkalpak Avatar answered Oct 26 '25 22:10

gkalpak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!