-1

I have two scopes $scope.job and $scope.jobs

I have var job;

If $scope.job is undefined I would like $scope.jobs to work under job so it would be var job = $scope.jobs but if $scope.job is defined I want to write it to that variable too.

if ( $scope.job ) {
    var job = $scope.job; 
} else {
    var job = $scope.jobs; 
}

But in shorthand

ngplayground
  • 20,365
  • 36
  • 94
  • 173

3 Answers3

1

I want to leave short comment but now I understand that will be better if I explain.

var job = $scope.job || $scope.jobs;

undefined == false; // prints true

So that's how it works.

If $scope.job == undefined == false || $scope.jobs == {...} == true.

If job will be undefined - it will be false so or operand returns true value.

ivarni
  • 17,658
  • 17
  • 76
  • 92
Eugene Obrezkov
  • 2,910
  • 2
  • 17
  • 34
0

So if i understand what you mean:

if ($scope.job)
  var job = $scope.job;
else
{
  var job = $scope.jobs;
  $scope.job = $scope.jobs;
}

well, shorthand then:

var job = $scope.job = $scope.job || $scope.jobs;
DoXicK
  • 4,784
  • 24
  • 22
0

Or you can use ternary operator

var job = $scope.job ? $scope.job : $scope.jobs

or

var job = $scope.job == undefined ? $scope.job : $scope.jobs
Mike S.
  • 1,995
  • 13
  • 25