How to create an angularjs filter that displays HTML

After reading Step by Step on AngularJS step 9, I created my own AngularJS filter, which should convert logical data to html.

Here is my filter code:

angular.module('phonecatFilters', []).filter('iconify', function () { // My custom filter return function (input) { return input ? '<i class="icon-ok"></i>' : '<i class="icon-remove"></i>'; } }); 

Here is my HTML code:

 <dt>Infrared</dt> <dd>{{phone.connectivity.infrared | iconify }}"></dd> 

The problem is that borwser displays the return value literally as:

 <i class="icon-ok"></i> 

not like the icons (or html displayed) that should appear.

Here is a JSFiddle example

I think that during this process a certain sanitation arises.

Is it possible to disable this cleanup for this particular filter?

I also know how to display icons without returning HTML output from the filter, but simply โ€œgoodโ€ or โ€œdeleteโ€ the text, which I can then replace with:

 <i class="icon-{{phone.connectivity.infrared | iconify}}"><i> 

but thatโ€™s not what I want.

+82
angularjs
Nov 06
source share
3 answers

You should use the ng-bind-html directive (you need to import the sanitize module and js file): https://docs.angularjs.org/api/ng/directive/ngBindHtml

 <span ng-bind-html='phone.connectivity.infrared | iconify'></span> 

You also need to import CSS ( Bootstrap , I think) to be able to see the icon when it works.

I have provided a working example .

+104
Nov 06
source share

If I do not read it wrong, you are approaching the wrong way

I think ng-class is the directive needed for this job, and is safer than rendering for the class attribute.

in your case, just add an object string with id strings as a class and value as an evaluated expression

 <i ng-class="{ 'icon-ok':!phone.connectivity.infrared, 'icon-remove':phone.connectivity.infrared }"></i>' 

on the side of the note, you should only use directives (built-in and custom) to control html / dom, and if you need more complex html rendering, you should look for the directive instead

+16
04 Oct '13 at 8:41
source share

Try this filter.

 filter('trust', ['$sce',function($sce) { return function(value, type) { return $sce.trustAs(type || 'html', value); } }]); 

Gist link

+7
Jul 16 '15 at 18:55
source share



All Articles