Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create angularjs filter which outputs HTML

Tags:

angularjs

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.

like image 259
Pavel Kostenko Avatar asked Nov 06 '12 12:11

Pavel Kostenko


People also ask

What is the correct way to apply filter in AngularJS?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.


2 Answers

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.

like image 138
Guillaume86 Avatar answered Nov 16 '22 00:11

Guillaume86


Unless I am reading it wrong, you are approaching in the wrong way.

I think ng-class is the directive you need for this job and is safer than rendering to class attribute.

In your case just add object string with the id strings as the class and the value as the evaluated expression.

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

On a side note, you should only use directives (built-in and custom) to manipulate html/dom and if you needed a more complex html render you should look at directive instead.

like image 33
Gerard Avatar answered Nov 16 '22 00:11

Gerard