Saqib Ali Saqib Ali - 2 months ago 18
AngularJS Question

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

I have the following AngularJS template.

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


Can I simplify or clean-up or combine these three
ng-if
statements??

condition1
,
condition2
and
condition3
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

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:

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

Or you could also use ng-switch.

Comments