-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
  • 18,559
  • 34
  • 93
  • 168

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,269
  • 16
  • 76
  • 91
Eugene Obrezkov
  • 2,739
  • 2
  • 16
  • 32
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,644
  • 23
  • 21
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,805
  • 14
  • 25