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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With