aalbagarcia
aalbagarcia

Reputation: 1044

How to output html from a filter in Angular

I have defined a filter as follows

@angular.module('extcomFilters',[]).filter('status_icon',()->
  (input) ->
    if input <=0
      "<i class='icon-thumbs-down'></i>"
    else
      "<i class='icon-thumbs-up'></i>"
)

so depending on the status, I can get one icon or the other one. I'm using it inside a span tag using the ng-bind-html-unsafe directive:

 <span data-ng-bind-html-unsafe="{{status | status_icon}}"></span>

Instead of having the icon displayed inside the span element, I'm getting this:

<span data-ng-bind-html-unsafe="&lt;i class='icon-thumbs-up'&gt;&lt;/i&gt;"></span>

Any idea of what I'm doing wrong?

Thanks!!

Upvotes: 2

Views: 2282

Answers (2)

aalbagarcia
aalbagarcia

Reputation: 1044

I solved it by injecting $sce service in my filter:

filter('status_icon',['$sce', ($sce)->
  (input) ->
    if input == null or input == ''
      return $sce.trustAsHtml("<i class='icon-thumbs-down'></i>")
    else if input >= 0
      return $sce.trustAsHtml("<i class='icon-thumbs-up'></i>")
    else if input < 0
      return "loading..."
])

and using ng-bind-html in the span element:

 <span data-ng-bind-html="status | status_icon"></span>

Upvotes: 4

Darryl
Darryl

Reputation: 1451

Did you include the Sanitize module in your controller? Without it the attribute will just be interpreted as a non-angular attribute. It appears in your example that you just need ng-bind-html, so perhaps give that a try.

Upvotes: 2

Related Questions