Search code examples
javascriptangularjsformsng-class

how to write ng-class object to compare complicated conditions?


There is a form to let the user input some fields in 4 steps. For each step there maybe several fields. If all the fields shown in current step are valid this step will show green colour, otherwise it will show red.

For step 3, there are at most 4 fields shown at the same time, let's say A,B,C,D. Assume each valid value is a,b,c,d accordingly.Because some fields will show/hide according to previous selection.The final logic condition should be abcd||abc||ab||a||bcd||bc||d(abcd means a&&b&&d&&c). i'm using the ng-class with object to change the css color, the snippet is like below:

ng-class="{
"green": abcd||abc||ab||a||bcd||bc||d,
"red": !(abcd||abc||ab||a||bcd||bc||d)
}"

As you can see, this is really ugly solution...Is there elegant way to solve this?


Solution

  • You could pass ng-class a function

    ng-class="{'green': isValid(), 'red': !isValid()}"
    

    and create the funcion in your controller

    $scope.isValid=function(){ 
        return abcd||abc||ab||a||bcd||bc||d;
    }