Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render raw html with AngularJS?

I'm creating an AngularJS single page application. The data will be fetched from a webservice in json-format.

The problem is that some text elements come with preformatted html tags

json output:

{
   "text": "<p><span style="text-decoration: underline;"><strong>test text</string></span></p>"
}

Now how can I display this text and render the html directly, so that only "test" is shown to the user and the rest serves as markup?

<h1>{{data.text}}</h1>
like image 566
membersound Avatar asked Aug 07 '15 14:08

membersound


People also ask

How can you integrate AngularJS with HTML?

AngularJS Introduction. AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.

Can we use HTML in angular?

With AngularJS, you can include HTML from an external file.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.


2 Answers

You need to add ng-bind-html="data.text" to your h1 tag.

Your html would look like:

<h1 ng-bind-html="data.text"></h1>

Documentation: ngBindHtml

like image 182
MHX Avatar answered Sep 21 '22 18:09

MHX


Update2: is it possible to strip the html for you? It could be done so:

angular.module('myApp.filters', []).
   filter('htmlToPlaintext', function() {
      return function(text) {
         return String(text).replace(/<[^>]+>/gm, '');
      };
   }
);

And you html:

<div>{{myText | htmlToPlaintext}}</div>

See more information: angularjs to output plain text instead of html

Update: do you really need the html from your json? It's better to store your html in the views and get the data from your json. Nice separation and very easy to use.

It's possible, but not so easy as non-html (great security).

In Angular 1.3 you need as follows:

<div ng-bind-html="htmlBind"></div>

In your controller add this:

$scope.htmlBind = $sce.trustAsHtml('<span>Hi, I am <em>Joe</em>');

Explanation: you see the $sce:

$sce is a service that provides Strict Contextual Escaping services to AngularJS.

trustAs(type, value)

Delegates to $sceDelegate.trustAs. As such, returns an object that is trusted by angular for use in specified strict contextual escaping contexts (such as ng-bind-html, ng-include, any src attribute interpolation, any dom event binding attribute interpolation such as for onclick, etc.) that uses the provided value. See * $sce for enabling strict contextual escaping.

Read more here:

  • https://docs.angularjs.org/api/ng/service/$sce
  • AngularJS : Insert HTML into view
like image 28
schellingerht Avatar answered Sep 19 '22 18:09

schellingerht