How to create angularjs filter which outputs HTML

Issue

After reading AngularJS tutorial step-9
I have created my own AngularJS filter, which should convert boolean data into 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 returned value literally as:

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

not as icons (or rendered html) that should appear.

Here is JSFiddle example

I think that some sanitisation occurs during this process.

Is it possible to turn this sanitization off for this specific filter?

Also I know how to display icons by not returning HTML output from filter but rather just ‘ok’ or ‘remove’ text which I can then substitute to:

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

but this is not what I want.

Solution

You should use the ng-bind-html directive (require 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 the CSS (Bootstrap I guess) to be able to see the icon when it works.

I have provided a working example.

Answered By – Guillaume86

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published