I'm trying to display an HTML string in my Angular view.
At first, I naively tried this :
<p>{{ad.text}}</p>
$scope.ad = { 'text' : '<a href="#">Link</a>'}; // Dynamically fetched, etc. This is just an example text
But this just displays <a href="#">Link</a>
in the view, not : link.
After some research, I stumbled upon ngSanitize. I tried it, but it totally strips off all HTML code to leave just raw text. Pretty secure indeed. A bit too much, actually. Anyway, ngSanitize is now outdated.
This SO post indicates that now the $sce service has to be used instead of ngSnitize.
Following these various solutions, here is what I came up with :
HTML
<p ng-bind-html="htmlAdText"></p>
JS
$scope.ad = { 'text' : '<a href="#">Link</a>'};
$scope.htmlAdText = $sce.trustAsHtml($scope.ad.text);
But this error comes in the console :
ReferenceError: $sce is not defined
What bugs me is that the $sce service is supposed to be part of Angular's core since v1.2, and I'm using v1.3.9.
What's going on here? Does anyone have a definitive method to display HTML in an AngularJS view ( without filters that just leave the raw text) ?
You can use the ascii code for   in a string. Alt-255. This will correctly render as an  . This was not the question how to insert non breaking space character in AngularJS but how to add html entities like < , > or it's obvious that you can insert any character into text.
The AngularJS ng-bind-html directive is used to bind content to an HTML element securely. It evaluates the expressions and inserts the resulting HTML into the element in a secure way. By default, the resulting HTML content will be sanitized using the $sanitize service.
Just get rid of the display: none; from your CSS. AngularJS is in control of showing/hiding that div. If you want to hide it by default, just set the value of scope. myvalue to false initially - which you're already doing.
AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag. AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
Don't forget to inject it into controller, for instance:
app.controller('mainCtrl', [ '$scope', '$sce', function($scope, $sce){
$scope.ad = { 'text' : '<a href="#">Link</a>'};
$scope.htmlAdText = $sce.trustAsHtml($scope.ad.text);
}]); //End Controller
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