Saqib Ali Saqib Ali - 1 year ago 73
AngularJS Question

Can I clean up these ng-if statements in AngularJS templates?

I have the following AngularJS template.

<td ng-if="condition1">
Hello World
<td ng-if="condition2">
A <a ui-sref="mystate1({a: 1, b: 2})"></a>
<td ng-if="condition3">
B <a ui-sref="mystate1({a: 1, b: 2})"></a>

Can I simplify or clean-up or combine these three

are mutually exclusive. However, they are not based off a single expression so a switch statement won't work? Can I use an if-then-else construct?

Answer Source

If they are mutually exclusive, then yes, you can simplify condition2 and condition3 and only use one condition for both (since the output is the same).

EDIT: Based on your update, you could simplify the logic like this:

<td ng-if="condition1">
  Hello World
<td ng-if="condition2 || condition3">
  {{condition2 ? 'A' : 'B'}}
  <a ui-sref="mystate1({a: 1, b: 2})"></a>

Or you could also use ng-switch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download