如何为ng-class设置多个‘或’条件?Angular样式绑定问题求助
Hey there, let's break down why your code isn't behaving as expected—you've got a couple of syntax and redundancy issues to fix:
1. Incorrect ng-class Syntax
Your current ng-class expression has invalid syntax. When defining multiple class-condition pairs in the object, each pair needs to be separated by a comma, and you can't use || to chain them like that. Each class name should map directly to its own boolean condition.
Wrong:
<td ng-class="{IsGreen: s.InformationForm == 'Form Completed' || IsMaroon: s.InformationForm == 'Fill Form'}">
Right:
<td ng-class="{IsGreen: s.InformationForm === 'Form Completed', IsMaroon: s.InformationForm === 'Fill Form'}">
(Pro tip: Use === instead of == for strict equality checks in AngularJS—it avoids unexpected type coercion issues.)
2. Redundant <a> Tags
You don't need two separate <a> elements for each condition. Since both have the same class and href, you can combine them into one element with a single conditional check (or even skip the conditional if these are the only possible values for s.InformationForm).
Simplified Combined Version:
<td ng-class="{IsGreen: s.InformationForm === 'Form Completed', IsMaroon: s.InformationForm === 'Fill Form'}"> <a href="javascript:void(0);" class="IsColorWhite" ng-if="s.InformationForm === 'Form Completed' || s.InformationForm === 'Fill Form'"> {{s.InformationForm}} </a> </td>
Even Cleaner (If Values Are Mutually Exclusive):
If s.InformationForm only ever has those two values, you can drop the ng-if entirely—no need to hide it if there's no other case:
<td ng-class="{IsGreen: s.InformationForm === 'Form Completed', IsMaroon: s.InformationForm === 'Fill Form'}"> <a href="javascript:void(0);" class="IsColorWhite">{{s.InformationForm}}</a> </td>
Final Notes
Make sure your CSS classes IsGreen, IsMaroon, and IsColorWhite are properly defined in your stylesheet (e.g., IsGreen { background-color: green; } or whatever styling you intend—since you're applying the class to the <td>, it will affect the cell's styling, and the white text class on the link will make the text stand out).
内容的提问来源于stack exchange,提问作者3 rules

