Christopher
Christopher

Reputation: 3469

AngularJS - Default value when var is undefined

I'm trying this:

$scope.items = {
    current: item.number || 1
};

And i'm getting: Error: item.number is undefined

How to set the current to 1 when item.numberis undefined?

Upvotes: 0

Views: 58

Answers (3)

James Brierley
James Brierley

Reputation: 4670

This errors because item itself is undefined. Try:

current: item && item.number ? item.number : 1

If it's possible for item.number to be 0, change this to:

current: item && item.number !== undefined ? item.number : 1

0 is falsey so would be overwritten by 1 in the first case.

Upvotes: 4

Tarun Dugar
Tarun Dugar

Reputation: 8971

Just use a simple if-else:

$scope.items = {}
if(item.number == undefined) {
    $scope.items.current = 1;
}
else {
    $scope.items.current = item.number;
}

Upvotes: 0

GeoffreyB
GeoffreyB

Reputation: 1839

Try this:

$scope.items = {
  current: (item && typeof item.number != "undefined") ? item.number : 1
};

Upvotes: 1

Related Questions