5

I need to add 2 class names in specific conditions to an element:

ng-class="(commentItem.comment | escapeHtml | direction)"

works for the first, getting text content of given html string using the "escapeHtml" filter and then getting direction of the text using the "direction" filter. now I need to add another class to the same element this way:

ng-class="{'hidden': commentItem.isEditing}"

how to mix them both in a single ngClass directive?

Note
I think it's not possible to use the

{"exp1": condition1, "exp2": condition2}

because in the first condition, the filter returns the class name for me.

Reyraa
  • 4,174
  • 2
  • 28
  • 54

1 Answers1

0

Take a look at this plnkr.

The documentation for ng-class regarding the argument states:

Expression to eval. The result of the evaluation can be a string representing space delimited class names, an array, or a map of class names to boolean values.

It does not have to be a literal string or map or array. You can have a function return an array of classes like this:

ng-class="getClasses()"

And use whatever you like to construct the array in your controller. If you need filters use the $filter service.

If you don't want to use a controller function to handle view details you can pass an array to ng-class and for each element write na expression that returns a class name or an empty string:

ng-class="[!!redbg ? 'redbg' : '', 'gr' + 'een']"
user2847643
  • 2,893
  • 14
  • 22
  • I think creating a function which is not a controller nor a directive is an anti pattern approach. I used to resolve view-related issues inside view. cause if I didn't, I would've had a long list of utility functions by now. If you're sure there is no way to mix such different conditions, then I prefer to step back and prevent such a situation to happen. Thank you – Reyraa Apr 15 '15 at 12:19
  • How about: `

    Hello Plunker!

    `. So use one expression for each element of an array and return a string with class name or empty. I don't think you will be able to use filters that way though.
    – user2847643 Apr 15 '15 at 12:55
  • One last option you have is to use both `ng-class` and `class` on a single element: `ng-class="{xxx: yyy}" class="{{expression returning class string}}"` – user2847643 Apr 15 '15 at 13:02
  • This is a better option. I used it. Thank you. Please add it in your answer – Reyraa Apr 15 '15 at 13:24