Reputation: 62596
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.
Upvotes: 4
Views: 4165
Reputation: 3856
@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);
});
}
};
});
Upvotes: 1
Reputation: 48212
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.
Upvotes: 3
Reputation: 795
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.
Upvotes: 3
Reputation: 1272
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">
Upvotes: 0