How to make raw html using anguarjs?

I am creating a single page angularjs application. Data will be retrieved from the web service in json -format.

The problem is that some text elements have pre-formatted 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 the user only displays the β€œtest” and the rest is the markup?

 <h1>{{data.text}}</h1> 
+5
source share
3 answers

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

Your html will look like this:

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

Documentation: ngBindHtml

+6
source

Update2: is it possible to remove html for you? This can be done like this:

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

And you html:

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

See more info: angularjs for plain text output instead of html

Update: do you really need html from json? It is better to store your html in views and receive data from your json. Good separation and very easy to use.

It is possible, but not as simple as non-html (great security).

In Angular 1.3, you need the following:

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

In the controller, add the following:

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

Explanation: you see $ sce:

$ sce is a Strict Contextual Escaping service for AngularJS.

trustAs (type, value)

Delegates to $ sceDelegate.trustAs. Thus, an object that Angular trusts for use in the specified strict contextual escape contexts (such as ng-bind-html, ng-include, any interpolation of src attributes, any interpolation of the dom binding attribute, e.g. for onclick, etc. is returned .) which uses the provided value. See * $ Sce for strict contextual escaping.

More details here:

+3
source

Try using https://docs.angularjs.org/api/ng/directive/ngBind

 <script> angular.module('bindExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.name = 'Whirled'; }]); </script> <div ng-controller="ExampleController"> <label>Enter name: <input type="text" ng-model="name"></label><br> Hello <span ng-bind="name"></span>! </div> 
-1
source

All Articles