Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - conditional formatting using a filter

Tags:

angularjs

I am trying to apply conditional filltering in my html using an Angular filter:

Filter in JS file:

angular.module('myFilter', []).filter('conditionFormat', function () {
    return function (input) {
        return (input 
            ? '<span style="color:#008000; font-weight:bold;">The statement is true</span>' 
            : '<span style="color:#008000; font-weight:bold;">The statement is <span style="color: #FF0000;">NOT</span> true</span>');
    };
});

HTML Code:

<td>
  <span ng-bind-html="{{statement.IsTrue | conditionFormat}}"></span>
</td>

The output of this is literally:

<span style="color:#008000; font-weight:bold;">The statement is true</span>

Is there a way to encode the return string in HTML? or perhaps another way of accomplishing this?

thanks in advance.

like image 838
noobie Avatar asked Jan 29 '26 01:01

noobie


1 Answers

It would be cleaner to do this using CSS classes and ngClass:

<span class="normal">The statement is </span>
<span ng-class="{warn:statement.IsTrue}">{{statement.IsTrue}}</span>

With appropriate definitions for the CSS classes 'normal' and 'warn'.

Alternatively, just use ngShow and ngHide to show one block of HTML and to hide the other. For the most part, in Angular, you manipulate a model and the view renders it using conditional directives; you rarely need to manipulate the HTML directly.

like image 73
Ian Mercer Avatar answered Jan 30 '26 14:01

Ian Mercer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!