Search code examples
htmlcssangularjsvalidationng-class

Changing class combinations based on multiple conditions


I have few style classes defined in my style sheet as like the following:

.left-align{
  /* some styles here */
}
.right-align{
  /* some styles here */
}
.validate-error{
  /* some styles here */
}

Based on the type of data in the class I need to align the content left or right, and also I wanted to call a method which will validate my data in the control, if validation fails need to append the validate-error class as well to the ng-class. I gone through different SO threads and other articles and QA sites that titled as multiple conditions in ng-class but nothing found working in my scenario, I have tried the following based on the references:

ng-class="{!vm.validate()?'validate-error': vm.isNumericField?'right-align':'left-align'}"

But this will not align the content to the right even isNumericField is true when validate() returns false.

In short, I need to add left-align or right-align depends on the isNumericField property and also validate-error if validate() returns false.

 "isNumericField?{'left-align':'right-align'} + 'validate-error':validate()"

Please anyone let me know if there any way to achieve this:


Solution

  • You can specify "map" of class names to boolean values:

    ng-class="{'validate-error': !vm.validate(), 'right-align': vm.isNumericField, 'left-align': !vm.isNumericField}"