snaggs
snaggs

Reputation: 5713

if statement in html angularjs

I have a table and I want to write basic if statement into <td>.

<tbody>
<tr ng-repeat="item in pagedItems[currentPage]">
  <td>{{item.id}}</td>
  <td>{{(item.name == "name 12" && 'xxx') || item.name}}</td>
  <td>{{item.description}}</td>
  <td>{{item.field3}}</td>
  <td>{{item.field4}}</td>
  <td>{{item.field5}}</td>
</tr>
</tbody>

What I try to do is: if item.name == "name 12" => set empty string otherwise leave it as is.

Something like that:

 <td>{{(item.name == "name 12" && '') || item.name}}</td>

However it works only if I put some String like 'xxx' in my case but with '' it doesn't work.

Here is a demo in Fiddle

Upvotes: 0

Views: 63

Answers (2)

KayakDave
KayakDave

Reputation: 24676

Angular added the ternary (conditional) operator in 1.1.5 (test ? ifTrue : ifFalse) which you can use like this:

<td>{{((item.name == "name 12") ? "" : item.name)}}</td>

Which, if (item.name == "name 12") is true will return "" and it's false will return item.name

updated fiddle

Upvotes: 3

Pascal Ockert
Pascal Ockert

Reputation: 984

An empty string evaluates to false, so item.name will be used instead of the empty string. Instead of the empty string you can use single space, that should work:

<td>{{(item.name == "name 12" && ' ') || item.name}}</td>

Or if you really need an empty string, negate it:

<td>{{(item.name != "name 12" && item.name) || ''}}</td>

Upvotes: 2

Related Questions