Skip to content Skip to sidebar Skip to footer

Fa Fa-icons In Ng-class With Ternary Operator (angular.js 1.x)?

May be my this SO not clear, so again trying to ask what i really want(forgive,if its still not clear). Trying to reduce multiple html snippets into single line. Actual blocks look

Solution 1:

ng-class using the ternary operator should be formatted like below

ng-class="variableToEvaluate ? 'class-if-true' : 'class-if-false'">

So you need to do all your evaluations in the first part of the statement, then apply classes appropriately.

Solution 2:

I would say the brackets are wrong. But it is very hard-to-read ternary operator.

To get better insight about the logic, you can rewrite this ternary logic into a method in controller. Like following:

functiongetFaIcon(presentHeader, previousHeader) {
  var result = '';
  if (presentHeader != previousHeader || presentHeader =='itemID') {
    result = 'fa fa-thumbs-up';
  } else {
    if (alterTblType && presentHeader=='itemID') {
      result = 'fa fa-thumbs-down';
    } elseif (!alterTblType && presentHeader=='itemID') {
      result = 'fa fa-thumbs-up';
    }
  }

  return result;
}

It can also be simplified because in two cases you return the same value 'fa fa-thumbs-up'.

Also when it is a method, you can but some caching to the method results, which might be extremly useful to speed the digest cycle up.

You can debug it and realize what's the actual problem there.

In your HTML you call it like this:

ng-class="getFaIcon(presentHeader, previousHeader)">

Solution 3:

Maybe you can use something like this:

<spanng-class="{'classname' : condition}"></span>

For example:

<spanng-class="{'icon1-class': obj.value1 == 'someothervalue' || obj.value2 == 'other-class'}"></span>

Post a Comment for "Fa Fa-icons In Ng-class With Ternary Operator (angular.js 1.x)?"