0

I have conditional parameters on ui-router because I am using the same screen in different places in an app. I have to write logic to check which $stateParams value I have assigned to paramId. I have tried with if and else.

Is there a better approach to achieve this task?

$scope.challengesDTO = {
    challengeTypeLkupCode: 'RA_CHLNG_TYP_PRC'
};

var paramId = $stateParams.processId ? $stateParams.processId : $stateParams.assessmentId;

if ($stateParams.processId) {
    $scope.challengesDTO.challengeTypeLkupCode = 'RA_CHLNG_TYP_PRC'
} else if ($stateParams.assessmentId) {
    $scope.challengesDTO.challengeTypeLkupCode = 'RA_CHLNG_TYP_RSKASES'
}
iggymoran
  • 4,059
  • 2
  • 21
  • 26
hussain
  • 6,587
  • 18
  • 79
  • 152

3 Answers3

1

Consider The Null-Coalescing Operator

You should be able to replace your ternary operator with the null coalescing operator in Javascript ||, which essentially a logical 'OR' statement :

// This will set it to processId (if available), otherwise assessmentId
var paramId = $stateParams.processId || $stateParams.assessmentId;

A Ternary (if you want one)

However, if you were just worried about setting your challengeTypeLkupCode property, you could use the following, which would set it depending on if processId existed or not :

// Set your lookup type depending if processId exists or not
$scope.challengesDTO.challengeTypeLkupCode = ($stateParams.processId) ? 'RA_CHLNG_TYP_PRC' : 'RA_CHLNG_TYP_RSKASES';

For readability purposes, you may be best off just using an if statement as seen in your initial code.

Community
  • 1
  • 1
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • is there way to check value assigned to `paramId` is`processId` or `assessmentId`? – hussain Apr 28 '16 at 17:11
  • Not without performing another comparison to explicitly see if `paramId` is equal to `processId` or `assessmentId`. This is why an if-statement may be preferred as you can perform a single comparison and perform all of your logic related to the comparison within the body of the if-statement. – Rion Williams Apr 28 '16 at 17:18
0

For the if else condition u mentioned above u can try-

$scope.challengesDTO.challengeTypeLkupCode=$stateParams.processId?'RA_CHLNG_TYP_PRC':$stateParams.assessmentId?'RA_CHLNG_TYP_RSKASES':"Default value u want to give";
misss-popcorn
  • 591
  • 2
  • 12
0

The first part goes with a logical OR ||

var paramId =  $stateParams.processId || $stateParams.assessmentId;

The second part is with a nested ternary operator ?: and returns the value itself if no comparison becomes true.

$scope.challengesDTO.challengeTypeLkupCode = $stateParams.processId ?
    'RA_CHLNG_TYP_PRC' :
    $stateParams.assessmentId ?
        'RA_CHLNG_TYP_RSKASES' :
        $scope.challengesDTO.challengeTypeLkupCode;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392