Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying HTML in an Angular 1.3.9 view with $sce

Tags:

angularjs

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) ?

like image 881
Jeremy Thille Avatar asked Mar 04 '15 11:03

Jeremy Thille


People also ask

What is &nbsp in angular?

You can use the ascii code for &nbsp in a string. Alt-255. This will correctly render as an &nbsp. This was not the question how to insert non breaking space character in AngularJS but how to add html entities like &lt; , &gt; or &nbsp; it's obvious that you can insert any character into text.

How does ng-bind-HTML work?

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.

How to hide and show div in AngularJS?

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.

What is Angular min JS?

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.


1 Answers

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
like image 172
Samir Alajmovic Avatar answered Oct 22 '22 13:10

Samir Alajmovic