Suavocado
Suavocado

Reputation: 969

Set default variable using directive

I'm looping through an array of objects using ng-repeat and printing it to a table in my view, but depending on what an api returns, I may not have a value for each attribute of each object. This results in a table with blank spaces. I would like for the blanks to simply show "0" rather than just be empty.

Is there a simple way to accomplish this without adding "0" values to the objects?

e.g

var rooms = [
    {room_num:'1', seats_available:'5'},
    {room_num:'2', seats_available:'12'},
    {room_num:'3'}
]

view:

<div ng-repeat='room in rooms'>
  <h1>Room:{{room.room_num}}</h1>
  <h2>Seats:{{rom.seats_available}}</h2>
</div>

would result in a blank for seats available in room 3. I would like it to just show 0.

Upvotes: 0

Views: 34

Answers (2)

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23512

Use the ternary operator.

<div ng-repeat='room in rooms'>
   <h1>Room:{{room.room_num}}</h1>
   <h2>Seats:{{room.seats_available ? room.seats_available : "0" }}</h2>
</div>

You could also just use ||. Which will work the same. However I think it's not great convention to do so.

<div ng-repeat='room in rooms'>
   <h1>Room:{{room.room_num}}</h1>
   <h2>Seats:{{room.seats_available || "0" }}</h2>
</div>

Upvotes: 2

Petr Averyanov
Petr Averyanov

Reputation: 9476

{{room.seats_available || "0" }}

(Be careful with Boolean values thow)

Upvotes: 0

Related Questions