18

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 ?

3 Answers 3

28

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>
Sign up to request clarification or add additional context in comments.

6 Comments

@blesh In this case +1 for you as well :-) You are also answering massive amount of questions!
Any reason why i can't define my directive as 'true-icon' ? Are directive names always camelcased ?
Angular just expects them to be camelcase. IIRC, they don't work if you declare them with the dashes.
Nice, thanks. I'm "scrubbing" \r\n and replacing it with <br/> so hopefully not violating the intended use of filters too much.
Why do you say this isn't what filters are for? In the Angular tutorial, the first example of custom filters does the same thing but with UTF characters instead of html markup.
|
6

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

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

2 Comments

+1 to you because we both said basically the same thing... and I see you around all the time.
I think your links are no longer valid.
0

Another approach I found for the case of converting \r\n to
is to use a small function and *ngFor.

In your ts file, add the function

splitLines(text: String): string[] {
  return text.split(/\r?\n/);
}

In html

<span *ngFor="let row of splitLines(multilineStringVariable)">
  {{row}}<br/>
</span>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.