4

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.

0

5 Answers 5

3

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.

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

Comments

3

Use ng-bind-html within <div>. Here is the example:

In your html file :

<div ng-controller="ngBindHtmlCtrl">
    <div ng-bind-html="myvar"></div>
</div>

In your js:

angular.module('ngBindHtmlExample', ['ngSanitize']) 

.controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) {
   $scope.myvar = 'Hello<br><br>World';
                 }]);

Example taken from AngularJs doc.

Comments

2

You can use ng-bind-html to bind to HTML directly. Here's the official documentation

Comments

1

@ExpertSystem is correct or if you're lazy like me you could do:

lrApp.directive('bindHtml', function () {
return {
    restrict: 'A',
    link: function (scope, elem, attrs) {
        scope.$watch(attrs.bindHtml,function(nv,ov){
            elem.html(nv);
        });
    }
};
});

Comments

0

1) Add the angular-sanitize.js library. This functionality used to be a part of the main library, but the Angular team has been splitting off sections to make it more modular.

2) Use the ng-bind-html tag:

<p ng-bind-html="myvar">

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.