Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular filter that generates html

I have a small angular filter that insert an (bootstrap) icon in place of a true value. It works but the html is encoded:

  var conApp = angular.module('conApp', []);
  conApp.filter('trueIcon', function($filter){
    return function(booleanValue){
        return booleanValue ? '<i class="icon-ok"></i>' : '';
    }
  });

Do i have to implement another filter to decode the html ? Is there an "angular" way of doing this ?

like image 920
Sucrenoir Avatar asked Feb 04 '13 17:02

Sucrenoir


People also ask

What is the correct way to apply filter in Angular?

Filters can be added to expressions by using the pipe character | , followed by a filter.

What does .filter do in Angular?

The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.

What is $scope in Angular?

AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.


2 Answers

You need to use ng-bind-html to render html.

<span ng-bind-html="foo | trueIcon"></span>

That said... that's really not what filters are for. Filters are more for scrubbing data being written to a view, rather than generating elements of the view/DOM itself. You'll probably be better off creating a directive for that:

app.directive('trueIcon', function() {
   return {
      restrict: 'E',
      template: '<i ng-class="{\'icon-ok\': value, \'icon-not-okay\': !value}"></i>',
      scope: {
         value: '='
      }
   };
});

<true-icon value="foo"></true-icon>
like image 195
Ben Lesh Avatar answered Oct 12 '22 21:10

Ben Lesh


AngularJS is sanitizing results of expression evaluation by default. To display HTML as markup you've got 2 options:

  • http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml (from the ngSanitize module)
  • http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe (I wouldn't recommend this one as it opens up potential security risks).

While the above will make your filter work, maybe you should consider turning it into a directive?

like image 27
pkozlowski.opensource Avatar answered Oct 12 '22 20:10

pkozlowski.opensource