check null,empty or undefined angularjs

前端 未结 7 377
广开言路
广开言路 2021-02-02 07:34

I am creating a project using angularjs.I have variable like

$scope.test = null
$scope.test = undefined
$scope.test = \"\"

I want to check all

相关标签:
7条回答
  • 2021-02-02 08:04

    You can do

    if($scope.test == null || $scope.test === ""){
      // null == undefined
    }
    

    if false, 0 and NaN can also be considered as false values you can just do

    if($scope.test){
     //not any of the above
    }
    
    0 讨论(0)
  • 2021-02-02 08:10
    if($scope.test == null || $scope.test == undefined || $scope.test == "" ||    $scope.test.lenght == 0){
    
    console.log("test is not defined");
    }
    else{
    console.log("test is defined ",$scope.test); 
    }
    
    0 讨论(0)
  • 2021-02-02 08:10

    You can also do a simple check using function,

    $scope.isNullOrEmptyOrUndefined = function (value) {
        return !value;
    }
    
    0 讨论(0)
  • 2021-02-02 08:12

    A very simple check that you can do:

    Explanation 1:

    if (value) {
     // it will come inside
     // If value is either undefined, null or ''(empty string)
    }
    

    Explanation 2:

    (!value) ? "Case 1" : "Case 2"
    

    If the value is either undefined , null or '' then Case 1 otherwise for any other value of value Case 2.

    0 讨论(0)
  • 2021-02-02 08:13

    You can do simple check

    if(!a) {
       // do something when `a` is not undefined, null, ''.
    }
    
    0 讨论(0)
  • 2021-02-02 08:14

    You can use angular's function called angular.isUndefined(value) returns boolean.

    You may read more about angular's functions here: AngularJS Functions (isUndefined)

    0 讨论(0)
提交回复
热议问题