World" In my template, I...">

How to show html in angularjs template instead of string?

I have a variable in my area:

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

In my template, I use:

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

The problem is that myvar is showing literal text, while I want it to show line breaks. How to do it? Notice that I want to make sure that if in the future myvar is updated with other HTML, then what is shown on the page should be a "compiled" html, and not an alphabetic string with html tags in it.

+2
angularjs
May 19 '14 at 21:24
source share
5 answers

You can use ngBindHtml for this.
Keep in mind that because of Angular, strict conceptual escaping needs to either sanitize the content (using the optional ngSanitize module) or explicitly "trustedAsHtml" (using $sce.trustAsHtml() ). The latter is supposed to be used only for content that you know is safe (for example, nothing is defined by the user) and is not recommended in any case.

<sub> Note. ngSanitize is a non-core module and must be enabled separately:
<script src=".../angular.min.js"></script>
<script src=".../angular-sanitize.min.js"></script> Sub>

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 !'); }); 

<sub> Note that ngSanitize will filter the "inappropriate" content, and $sce.trustAsHtml will allow something. Sub>

See also this short demo .

+1
May 19 '14 at 10:34
source share

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

+2
May 19 '14 at 22:11
source share

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

In your html file:

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

In js :

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

Example from AngularJs doc.

+2
May 19, '14 at 22:13
source share

@ExpertSystem is correct, or if you are lazy like me, you can do:

 lrApp.directive('bindHtml', function () { return { restrict: 'A', link: function (scope, elem, attrs) { scope.$watch(attrs.bindHtml,function(nv,ov){ elem.html(nv); }); } }; }); 
+1
May 20 '14 at 2:54
source share

1) Add the angular -sanitize.js library. This functionality was used as part of the main library, but the Angular team separated the sections to make it more modular.

2) Use the ng-bind-html tag:

 <p ng-bind-html="myvar"> 
0
May 19 '14 at 22:13
source share



All Articles