Why my OR Operator in angularjs is not working?

I am using a if condition in angularjs to check is a status is != Delivered or status is != Canceled then alert a message

    if($scope.itemDeliveredStatus != "Canceled" || $scop.itemDeliveredStatus != "Delivered"))
{
    alert("Please set item status to Delivered! or Canceled!");
    return false;
}

3 answers

  • answered 2018-09-24 17:19 Charis The Programmer

    Typo on the second condition, you put $scop instead of $scope :

    $scop.itemDeliveredStatus
    

    and an extra ) at the end of that line which is not necessary

  • answered 2018-09-24 17:45 Jonathan Gagne

    In fact, you are missing the "e" at $scop, you have "))" that creates conflict as well.

    Other point, I guess you want triggers the alert when it is not Canceled or Delivered. So switch your logical as below and it will work. It will be cleaner and shorter.

    let $scope = {};
    $scope.itemDeliveredStatus = 'Not Delivered';
    if(!['Canceled', 'Delivered'].includes($scope.itemDeliveredStatus)) {
        alert("Please set item status to Delivered! or Canceled!");
    }

  • answered 2018-09-24 18:00 epascarello

    First you do have a typo, but that is only one small issue. The other is a logic problem.

    Your logic is wrong with the use of OR. Simple example below shows you that.

    var foo = "A";
    if (foo !== "A" || foo !== "B") {
      console.log("WHY?")
    }

    Why? Because you are saying that in order for this if statement to be true, the variable foo has to be equal to two things.

    You want it to say if foo does not equal A AND foo does not equal B, than show error.

    var foo = "A";
    if (foo !== "A" && foo !== "B") {
      console.log("WHY?")
    } else {
      console.log("Better!!!")
    }

    So with the two issues fixed, your code would look like:

    if ($scope.itemDeliveredStatus != "Canceled" && $scope.itemDeliveredStatus != "Delivered") { /*.. code */ }